Interview questions
Why do keys matter in lists?
Reconciliation identity and the index-key bug.
What is tested: whether you understand keys give React a stable identity per item so reconciliation knows which were added, removed or moved — enabling it to reuse and reorder DOM nodes instead of recreating them.
Keys are cloakroom tickets tied to the coat, not the peg; number by peg and shuffling the rack hands out the wrong coats.
Key concepts
1
With index keys, inserting or reordering shifts every item’s key, so React attaches existing state (an input’s value, a checkbox) to the wrong item. The canonical demo: a reorderable list of text inputs whose values follow the wrong rows.
index keys
2
The correct key is a stable, unique id from the data — never the index (unless the list is static) and never Math.random() (which forces full remounts every render).
stable, unique idMath.random()
3
Follow-up: "when is an index key acceptable?" — a static list that never reorders, filters or inserts.
Follow-up:
jsx
// Bug: checkbox state sticks to position, not the todo
{todos.map((t, i) => <Todo key={i} todo={t} />)}
// Fix: identity travels with the item
{todos.map((t) => <Todo key={t.id} todo={t} />)}