Key-based reconciliation
Keys are the primary mechanism React uses to identify which items have changed, been added, or removed in a list.Without keys
React compares elements position-by-position. Moving an item requires destroying and recreating elements, losing component state.
Key requirements
Keys must be stable, predictable, and unique among siblings. Using array indices as keys can cause subtle bugs when items are reordered or removed.
Reconciliation heuristics
React implements three core heuristics to achieve O(n) complexity:1. Component type heuristic
Elements of different component types produce fundamentally different trees.When React encounters different component types at the same position, it unmounts the old tree completely and builds a new one from scratch—no attempt to diff.
- The old
Countercomponent is unmounted - Its state is destroyed
- The
Timercomponent is mounted fresh - All child components are recreated
2. Element type heuristic
Similar to components, different element types trigger a rebuild.- Unmount the
divand its children - Create new DOM nodes for
articleand its children - Mount the new tree
3. List reconciliation heuristic
For lists of children, React uses keys to match elements.Processing new list
For each element in the new list, React checks if a matching key exists in the old list.
Performance implications
| Scenario | Without Keys | With Keys |
|---|---|---|
| Add item to start | O(n) unmount + mount | O(1) insert |
| Remove item | O(n) DOM operations | O(1) remove |
| Reorder items | O(n) destroy + recreate | O(n) move operations |
| Update one item | O(n) comparison | O(1) lookup + update |
While keys dramatically improve list performance, they have overhead. Only use keys for dynamic lists—static lists can rely on position-based reconciliation.
Fiber architecture preparation
The reconciliation heuristics lay the groundwork for React’s Fiber architecture, which adds:- Interruptible work: Break reconciliation into units that can be paused
- Priority-based updates: Handle different updates with different urgency
- Incremental rendering: Spread work across multiple frames
- Better error boundaries: Catch and handle errors during reconciliation
Fiber doesn’t change the reconciliation heuristics—it changes when and how reconciliation work is scheduled and executed.
Implementation guidelines
When implementing a reconciliation algorithm:- Build the heuristics first: Get component type, element type, and list reconciliation working
- Profile extensively: Measure both JavaScript execution time and DOM operation counts
- Handle edge cases: Fragments, portals, null, boolean, and array children
- Prepare for scheduling: Structure your reconciliation work to be pausable
In the Week 6 project, these heuristics form the core of your Virtual DOM library’s reconciliation algorithm, which you’ll stress test with 10,000+ dynamic nodes.