Answer guide
Read the answer guide
React uses the key to decide which component instance belongs to which item. With an index as the key, the item at position two is treated as the same component even after a reorder, insertion or deletion changes what data sits there. So local state, such as an input's typed text or an expanded panel, stays with the position and appears against another row. Keys should be unique among siblings and not random on each render, since that would recreate every component. An index is fine for a static list that is never reordered or filtered.
What the interviewer is assessing
Whether you understand how keys give component identity and preserve state across list updates.
A strong answer covers
- React uses the key to decide which component instance belongs to which item across renders.
- With an index key, reorder, insertion or deletion leaves the same instance at that position, so local state stays there against different data.
- Use keys that are unique among siblings and stable, such as an ID, and not random on each render.
- Index keys are acceptable only for a static list that is never reordered or filtered.
Common mistakes
- They say keys are only there to silence a warning and pick the index or a random value.
- They generate a new random key on each render, which destroys state and hurts performance.
Practise a follow-up
- When is an index key acceptable?
- What key would you use for rows that are not saved yet?