CodePark/ questions / Rendering & reconciliation
START PRACTICINGPRACTICE
Frontend question · React › Rendering & reconciliation

Why does React need key on list items, and why is using the array index often a bad idea?

Keys tell React which item is which between renders. When the list changes, React matches old and new children by key. So it can reuse the right component and DOM node and keep its state. Then it only inserts, removes or moves what changed.

An index key describes a position, not an item. Problems start when you insert at the top, delete, or reorder. Every item after the change gets a different index. React then reuses the wrong component for the wrong data. For example, text typed in one row's input, or a ticked checkbox, ends up attached to a different row. React also needs more DOM updates.

Use a stable unique ID from your data, like todo.id. Index keys are fine only for static lists that are never reordered or filtered. Never generate keys with Math.random() during render. Every item would then remount on every render.

  • Keys identify items across renders so React can match them.
  • Keys must be stable and unique among siblings.
  • Index keys break when you insert, delete or reorder items.
  • The symptoms are state attached to the wrong row and extra DOM work.
  • Random keys force every item to remount on every render.