Virtual DOM & Reconciliation
MedThe virtual DOM is a lightweight JavaScript object representation of the real DOM. When state changes, React creates a new virtual DOM tree, diffs it against the previous one, and computes the minimal set of DOM mutations needed. This reconciliation process uses O(n) heuristics to make updates efficient.
Interactive Visualization
Key Points
- Virtual DOM is a plain JS object tree describing the UI
- React diffs the new virtual tree against the previous one
- O(n) heuristics: different element types rebuild entire subtrees
- Keys help React identify moved, added, or removed children
- Batched DOM updates minimize expensive real DOM operations
- React Fiber architecture breaks reconciliation into interruptible work units
- Declarative model: describe what the UI should be, React figures out how
Code Examples
How Reconciliation Works
// Same type: React updates props, keeps the DOM node // Before: <button className="blue">OK</button> // After: <button className="red">OK</button> // React only updates className on the existing button // Different type: React destroys and rebuilds // Before: <div><Counter /></div> // After: <section><Counter /></section> // Counter state is lost because the parent type changed function App({ useSection }: { useSection: boolean }) { // Changing the wrapper type destroys Counter state const Wrapper = useSection ? 'section' : 'div' return ( <Wrapper> <Counter /> </Wrapper> ) }
Same element types are updated in place; different element types cause the old subtree to be torn down and rebuilt from scratch
Key-based Reconciliation
interface Item { id: string name: string } function ReorderableList({ items }: { items: Item[] }) { return ( <ul> {items.map((item) => ( // Key tells React which DOM nodes correspond to which data <li key={item.id}> <input defaultValue={item.name} /> </li> ))} </ul> ) } // When items reorder: [A, B, C] -> [C, A, B] // With keys: React moves DOM nodes (state preserved) // Without keys: React updates content in place (state mismatched)
Keys let React track list items across renders by identity rather than position, correctly moving DOM nodes when lists reorder
Common Mistakes
- Thinking the virtual DOM makes React faster than vanilla JS in all cases
- Changing element types accidentally and losing child component state
- Not understanding that reconciliation is per-component, not global
Interview Tips
- Explain the two heuristics: different types rebuild subtrees, keys match list children
- Discuss why O(n) is achievable instead of O(n^3) generic tree diff
- Know that React Fiber made reconciliation interruptible for concurrent features