React ยท Chapter 38 of 42

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.

Example 1 (jsx)
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>
  );
}
Output
Milk
Eggs

Using 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.
๐Ÿ’ก Note: React logs a warning when keys are missing, but not when they are merely index-based โ€” so review this yourself.

๐Ÿ“ Quick Quiz

1. What issue can index keys cause?

2. What should you use instead of index for dynamic lists?

3. When is using index as a key acceptable?