Keys and React's Reconciliation Algorithm
What you'll learn: How React uses keys as critical hints during its diffing process to efficiently match and reuse elements between renders.
The Reconciliation Process
When your component re-renders with a new list, React doesn't just throw away the old DOM and rebuild everything from scratch. Instead, it performs reconciliation — a diffing algorithm that compares the old virtual DOM tree with the new one to determine the minimal set of changes needed.
Keys are React's primary tool for making this process accurate and efficient.
Keys as Identity Hints
Without keys (or with unstable keys like array indexes), React matches list elements purely by position: "old item 1 maps to new item 1, old item 2 maps to new item 2." This positional matching breaks down when you reorder, insert, or remove items.
With stable keys, React can think: "Old element with key='user-42' matches new element with key='user-42', regardless of position." This allows React to:
- Reuse the actual DOM node (avoiding expensive recreation)
- Preserve component state (useState, focus, scroll position)
- Reuse the entire subtree of child components
The Efficiency Win
Think of keys like tracking numbers for packages. Without them, the postal service must assume packages stay in the same position on the truck. With tracking numbers, they can reorganize the truck efficiently while still delivering each package correctly.
When React finds matching keys, it skips diffing that entire subtree if props haven't changed — a massive performance win for complex list items.
Key Takeaway: Keys transform React's reconciliation from positional guesswork into precise element matching, enabling efficient subtree reuse and correct state preservation across renders.