Foundations: Virtual DOM & Reconciliation
Virtual DOM & Reconciliation: Understand the diffing algorithm and how React schedules DOM updates.
Directly manipulating the real browser Document Object Model (DOM) is computationally expensive. When a native DOM node mutates, the browser engine frequently recalculates styles, reflows the layout, and repaints composite layers.
React minimizes these costly operations through an in-memory abstraction: the Virtual DOM (VDOM), paired with a diffing algorithm known as Reconciliation.
Modern React executes this pipeline using the Fiber Architecture, transforming reconciliation from a synchronous, blocking stack traversal into an interruptible, priority-aware scheduling engine.
## 1. What the Virtual DOM Actually Is
The Virtual DOM is neither a Shadow DOM nor a mirror of the browser’s internal C++ DOM tree. It is simply a lightweight, plain JavaScript object representation of the UI tree retained in heap memory.
When you render a JSX component:
```js
```
React compiles and evaluates this into a plain JS node descriptor:
```js
{
type: 'div',
props: {
className: 'card',
children: [
{ type: 'h1', props: { children: 'Project Status' } },
{ type: 'p', props: { children: 'Active' } }
]
}
}
```
Creating and discarding thousands of these lightweight JavaScript objects takes a fraction of a millisecond. React uses these object descriptors to calculate the absolute minimum set of native mutations required before touching the real browser DOM.
## 2. The Reconciliation Diffing Heuristic (O(n3)O(n))
Finding the absolute minimum number of operations to transform one arbitrary tree of n elements into another has an optimal algorithmic complexity of O(n3). If a tree contains 1,000 elements, calculating the exact theoretical diff would require on the order of 1 billion comparison operations—far too slow for 60fps rendering.
React solves this by applying two practical heuristic assumptions, reducing the diffing cost to O(n):
```text
DIFFING HEURISTIC DECISION
│
┌─────────────────────────┴─────────────────────────┐
▼ ▼
```
## 1. Different Root Element Types? 2. Same Element Type?
• Tear down old tree completely • Retain underlying DOM node
• Destroy all child state • Diff and patch only changed
• Mount brand-new subtree attributes / props / styles
- **Heuristic 1:** Elements of Different Types Produce Different Trees
If the element type changes at a node (e.g., from <div> to <section>, or from <Header> to <Footer>), React does not attempt to match children. It unmounts the entire old branch, destroys all associated DOM nodes and component state, and constructs the new tree from scratch:
```js
// RENDER 1
{/* Counter state = 5 */}
// RENDER 2
{/* Counter unmounts and remounts: state resets to initial value */}
```
- **Heuristic 2:** Elements of the Same Type Retain Their DOM Nodes
When two elements share the same type, React keeps the existing browser DOM node and mutates only the modified attributes or style keys:
```js
// Before
// After
```
React preserves the <div> node, updates the className attribute, patches style.color = 'red', and leaves style.fontSize completely untouched.
## 3. The Critical Role of Keys in List Diffing
Without unique identifiers, React iterates over child lists by array index. If an item is prepended to the top of a list, index-based comparison forces React to mutate every single existing DOM node:
```js
// ❌ WITHOUT STABLE KEYS (or using Array Index as Key)
// Previous: [ Alice , Bob ]
// Next: [ Zara , Alice , Bob ]
// React matches index 0: changes text "Alice" -> "Zara"
// React matches index 1: changes text "Bob" -> "Alice"
// React appends index 2: mounts new node "Bob"
```
With Unique, Stable Keys:
When elements supply a key prop, React treats the key as an immutable identity tag:
```js
// ✅ WITH UNIQUE KEYS
// Previous: [ Alice , Bob ]
// Next: [ Zara , Alice , Bob ]
// React algorithm:
// 1. Matches key="z" -> Mounts new Zara at index 0
// 2. Matches key="a" -> Reuses existing node, moves position
// 3. Matches key="b" -> Reuses existing node, moves position
```
- **Why Index Keys Break:** Using key=\{index\} breaks whenever items are sorted, filtered, or inserted anywhere other than the end of the array. Child component state (such as text entered into an uncontrolled <input>) stays pinned to the array index, causing user inputs to drift to the wrong items.
## 4. The Engine: React Fiber Architecture
Prior to React 16, reconciliation used the Stack Reconciler. It traversed component trees recursively and synchronously. If a complex tree took 100ms to render, the JavaScript main thread was blocked for that entire duration—dropping frames and ignoring user keyboard or click input.
To fix this, React introduced the Fiber Engine.
### 4.1 What is a Fiber?
A Fiber is a specialized JavaScript object that represents a unit of work. Unlike a simple Virtual DOM element, a Fiber node maintains persistent pointers to its relatives, forming a mutable singly linked tree:
```text
[ Fiber: App ]
│ child
▼
[ Fiber: Header ] ──sibling──> [ Fiber: Main ]
│ child │ child
▼ ▼
[ Fiber: Logo ] [ Fiber: Article ]
```
Each Fiber node tracks:
- type and key
- **stateNode:** Reference to the actual native DOM element or component instance
- **child:** Pointer to its first direct child
- **sibling:** Pointer to its next immediate sibling
- **return:** Pointer back to its parent (the return destination after work finishes)
- **lanes:** Bitmask representing work priority
Because this tree uses pointers instead of JavaScript call-stack recursion, React can pause execution mid-tree, yield control back to the browser to paint or respond to user clicks, and resume work later without losing progress.
### 4.2 The Double Buffering Technique
React Fiber maintains two parallel trees in memory simultaneously:
```text
[ Current Tree ] <─── What is currently painted on the browser screen
│
(Cloned on state change)
│
▼
[ Work-In-Progress ] <─── Assembled & diffed silently in memory (Interruptible)
│
(Work finished)
│
▼
Commit to DOM ───────> Work-In-Progress swaps to become the new Current Tree
```
- **Current Tree:** Represents the UI state currently rendered to the native DOM.
- **Work-In-Progress (WIP) Tree:** Created during a state update. React constructs and diffs this tree offscreen. If higher-priority work (like typing into a text field) occurs while assembling the WIP tree, React discards the WIP tree, serves the input event, and restarts or resumes the background render.
- **The Swap:** Once the WIP tree is completely resolved, React applies the minimal changes to the native DOM in one fast, synchronous commit and swaps the pointer: current = workInProgress.
## 5. Modern Scheduling: Concurrent React & Lanes
Modern React does not treat all state updates with equal urgency. React categorizes updates into priority tiers using Lanes (represented internally by 32-bit integer bitmasks):
```text
HIGHEST PRIORITY ──> Discrete User Actions (click, keydown, input)
Transition Updates (filtering, tab switching via useTransition)
LOWEST PRIORITY ──> Deferred / Background (pre-fetching offscreen data)
```
```js
import { useState, useTransition } from 'react';
export function SearchDashboard() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [isPending, startTransition] = useTransition();
function handleType(e) {
// 1. High Priority (Urgent): Updates input value immediately (Zero typing lag)
setQuery(e.target.value);
// 2. Low Priority (Transition): React can pause this heavy diff if the user keeps typing
startTransition(() => {
const filtered = computeLargeDataset(e.target.value);
setResults(filtered);
});
}
return (
Project Status
Active
{isPending &&
);
}
```
## 6. The Two-Phase Pipeline: Render vs. Commit
Understanding the boundary between the Render Phase and the Commit Phase is essential to debugging unexpected component behavior:
| Characteristic | Render Phase (Reconciliation) | Commit Phase |
| --- | --- | --- |
| What happens | React invokes component functions, constructs Fiber WIP trees, and computes the diff list. | React applies structural mutations (appendChild, removeChild, attribute updates) to the real DOM. |
| Pacing | Asynchronous & Interruptible. Can yield execution back to the browser main thread. | Synchronous & Non-interruptible. Must finish in one continuous execution to prevent partial UI tears. |
| Side Effects Allowed? | Strictly Forbidden. No DOM writes, no network calls, no external variable mutations. | Permitted. useLayoutEffect runs synchronously; useEffect runs asynchronously immediately after. |
| In StrictMode | Re-invoked twice in development to verify component purity. | Executed once per completed update cycle. |Filtering records...
}