Question presented to candidate:
"React re-renders and produces a new element tree. How does it decide what to actually change in the DOM — and why does key matter so much?"
What a strong answer should cover:
- Reconciliation is React comparing the new element tree against the previous one and applying the minimum set of DOM operations. It is not comparing against the DOM itself.
- A general tree diff is O(n³), so React uses two heuristics to make it O(n).
- Heuristic 1 — different type means discard. If the element type at a position changed, React unmounts that subtree and mounts a new one. All state is lost.
- Heuristic 2 — keys identify siblings across renders. Within a list, the key tells React that "this is the same item as before", even if its position moved.
- Position is the default identity. Without keys, React pairs children by index — so inserting at the front makes every subsequent item look "changed".
- The practical consequence: index keys are wrong whenever the list can reorder, insert or delete, because component state and DOM state stay bound to the position, not the item.
- Same type and same key means React reuses the instance: state survives, only the changed props are applied.
- Changing a component's
keyis the deliberate way to reset its state.
Clarifying questions expected:
- "Can this list reorder, or have items inserted anywhere but the end?" — that decides whether index keys are acceptable.
- "Do the rows hold their own state — inputs, toggles, animations?"
Code / implementation expected: Optional. Demonstrating a checkbox landing on the wrong row is far more convincing than describing it.