How does React's reconciliation algorithm handle keys?
Why Interviewers Ask This
Senior React.js engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
Keys are central to React's reconciliation algorithm for efficiently updating lists. Without keys, React uses element position — if position n had a ListItem before and still does, React assumes it is the same instance and updates it in place. This is wrong for reordered lists — React might update a component with the wrong data, or preserve state from the wrong previous item. With keys: React associates key-identified elements across renders regardless of position. Algorithm: (1) For each key in the new list, check if a matching key exists in the old list. (2) If yes: update the existing component in place (preserve state, update props). (3) If the position changed: React can move the DOM node efficiently without recreating it. (4) Keys in old list with no match in new list: components are unmounted. (5) Keys in new list with no match in old: components are mounted. Keys must be stable across renders — if you generate keys with Math.random() or Date.now(), React sees every render as brand new and recreates all items. Stable IDs from your data model are ideal. Index as key: acceptable only for static lists that never reorder, add, or delete items.
Common Mistake
Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong React.js candidates.
More React.js Questions
View all →- Advanced What is the React Fiber architecture in depth?
- Advanced What are React rendering optimizations beyond React.memo?
- Advanced How do you implement an undo/redo system in React?
- Advanced What are React's concurrent features and how do Transitions work?
- Advanced How does React handle forms at scale?