Question presented to candidate:
"Why does React want a key on list items, and what actually goes wrong without a stable one?"
What a strong answer should cover:
- A key gives each list child a stable identity across renders, so React can tell whether an item moved, was added, or was removed — rather than comparing by position.
- Without keys React falls back to index, which is correct only if the list never reorders, has nothing inserted at the front, and nothing removed from the middle.
- The concrete failure: state and DOM attach to the wrong item. Uncontrolled input values, focus, scroll position, and component state all follow the key, not the data.
- Index keys are acceptable for a static list that never changes order — and genuinely wrong the moment it can.
- Keys must be stable, unique among siblings, and predictable. Not
Math.random(), which remounts everything every render. - Keys are not a prop —
keyis compiled to a separate argument, so a component cannot read its own key. - The flip side: deliberately changing a key resets state, which is the idiomatic way to reset a component on a prop change.
- Keys only need to be unique among siblings, not globally.
Clarifying questions expected:
- "Can this list reorder, or have items inserted or removed from anywhere but the end?"
- "Do the items have a stable id from the server?"
Code / implementation expected: Yes — a reorderable list with inputs, showing index keys mismatching.