How lists are diffed
When a list rerenders, the framework compares the old and new children to decide which to keep, move, or remove. The key prop is the identity it uses to match an old item to a new one. A stable, unique key per item makes that matching correct and cheap.
- The key identifies each item across renders.
- Matching keys let the framework reuse existing nodes.
- A changed key forces the item to remount fresh.
Why the index is risky
Using the array index as a key seems easy but breaks when items reorder, insert, or delete. The index stays the same while the item behind it changes, so state and dom can attach to the wrong row. A stable identifier from the data avoids this.
- Prefer a unique id from the data as the key.
- Avoid the array index when the list can reorder.
- Keys must be unique among siblings, not globally.
Correct keys prevent subtle bugs where input focus or local state jumps to the wrong item.
Key idea
The key prop gives list items stable identity for reconciliation, so use a unique data id rather than the array index to avoid mismatched state.