Why do you need a key when rendering a list (v-for / ng-repeat / React)?
Quick Answer
The key gives each list item a stable identity so the framework's diffing algorithm can match old and new items and move/reuse DOM nodes instead of recreating them. Without a stable key (or using the array index), reordering or removing items can leave component state attached to the wrong row.
The key is a stable identity for each item so the virtual-DOM diff can tell which old item corresponds to which new item and reuse the real DOM node instead of tearing it down. If I use the array index as the key, it breaks as soon as the list reorders or I remove an item — the framework reuses the node at that position, so any state in that row, like an input value or a component's local state, ends up on the wrong item. So I always key by a stable id from the data. It's the same idea as track by in AngularJS.
- Use a unique, stable id from your data (
item.id) — not the loop index, which changes when the list reorders or an item is inserted/removed. - The classic bug: a list of rows each with an input; you delete the second row; with index keys, the third row's input value visually “jumps” to the second position because the framework reused the DOM node and its state.
- AngularJS equivalent:
ng-repeat="item in items track by item.id"— without it, Angular tracks by value and throws on duplicates. - Correct keys also make list updates faster (targeted patches instead of re-rendering the whole list).