How React renders · core
Keys, identity and resetting state
A key is a child's identity among its siblings; with index keys, state and DOM stay attached to positions instead of items, and changing a key on purpose is the clean way to reset a component.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Keys only need to be unique among siblings, not globally.
- With
key={index}, inserting at the top, sorting or filtering moves data but not state: an input's typed text, focus and checkbox state stay on the old position, so they show on the wrong item. - Use a stable id from the data. If the API has none, create the id once when the item is created (for example
crypto.randomUUID()when adding), never during render. key={Math.random()}remounts every child on every render: slow, and focus and state are lost.- The index is acceptable only for static lists that are never reordered, filtered or prepended, and whose items have no state.
- Changing a key resets state on purpose:
<ProfileForm key={userId} />gives a fresh form when the user changes, with no effect needed. - React's list diff walks the new list once and reuses old fibers by key; moving the last item to the front makes React move all the others (a known cost).
The red pen
Common traps: mistake → fix
Mistake: "Keys help React tell items apart" (and nothing more)
Fix: say what breaks: state and DOM attach to the wrong item.
Mistake: "Keys must be globally unique"
Fix: unique among siblings is enough.
Mistake: "Index keys only cost performance"
Fix: the real bug is wrong state shown on the wrong row.
Easy to hard
Questions interviewers ask, easy to hard
- Why does React need keys?
- We insert an item at the top and the typed input text shifts to the wrong row. Why?
- When is the index acceptable as a key? What if the API has no id?
- How do you use a key to reset a component's state on purpose?
- Implement a keyed list diff: which items are inserted, removed or moved?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.