Keys vs Index Pitfalls
Using the array index as a key seems convenient, but it can cause subtle bugs when list items are reordered, inserted, or removed, since React uses keys to match items between renders.
Always prefer a stable, unique identifier from your data instead of the array index whenever the list can change order.
The problem
If item order changes but keys (indexes) stay the same, React may reuse the wrong DOM node's state, causing bugs like input values 'jumping' between rows.
The fix
Use a unique id field from your data, e.g. `key={item.id}`, so React can always track the correct DOM node.
const todos = [{ id: "a1", text: "Milk" }, { id: "b2", text: "Eggs" }];
function List() {
return (
<ul>
{todos.map(t => <li key={t.id}>{t.text}</li>)}
</ul>
);
}Milk
EggsUsing a stable id keeps list items correctly matched across renders.
Key points
- Array index as key can cause bugs when list order changes.
- Prefer a stable unique id from your data as the key.
- Wrong keys can cause state to be attached to the wrong item.
- Index keys are acceptable only for static, never-reordered lists.
