[FEE-702] Virtual DOM, Reconciliation & Diffing
INFO
This article explains what the Virtual DOM is, how frameworks like React use reconciliation and diffing to minimize real DOM operations, and why some frameworks (Svelte, Solid) have rejected the Virtual DOM entirely in favor of compiler-based or signal-based approaches.
Context
Manipulating the real DOM is expensive. Every document.createElement, every element.setAttribute, every parentNode.appendChild triggers internal browser bookkeeping -- style recalculation, layout, paint, compositing. When a single user interaction changes dozens of elements, naive imperative code that touches the DOM once per change produces far more work than necessary.
The Virtual DOM (VDOM) is an abstraction that solves this problem by interposing a lightweight in-memory representation of the UI between application code and the real DOM. Instead of mutating the DOM directly, the application describes the desired UI state as a tree of plain JavaScript objects. The framework then compares the new tree to the previous one (a process called diffing), computes the minimal set of real DOM operations needed, and applies them in a batch (a process called reconciliation).
How the Virtual DOM works
- Render: The application produces a new VDOM tree -- a tree of lightweight objects describing element types, props, and children.
- Diff: The framework compares the new tree against the previous tree node by node.
- Patch: Only the differences are applied to the real DOM -- an attribute change here, a node insertion there, a removal elsewhere.
This pattern decouples the "what should the UI look like" question (declarative) from the "how do I get the DOM from state A to state B" question (imperative). The framework handles the imperative part, freeing developers to think declaratively.
React: Fiber and heuristic diffing
React pioneered the Virtual DOM approach in 2013. Its current reconciliation engine, React Fiber (introduced in React 16), replaced the original synchronous, recursive tree-walk with an incremental, interruptible architecture.
The two heuristics. A generic tree diff algorithm runs in O(n^3) time -- impractical for UI trees with hundreds or thousands of nodes. React reduces this to O(n) by making two assumptions:
- Different element types produce different trees. If a
<div>becomes a<span>, React tears down the entire old subtree and builds a new one instead of trying to morph it. - Keys identify stable children across renders. When rendering a list, the
keyprop tells React which children are the same across renders, enabling it to reorder, insert, or remove efficiently.
Fiber's incremental model. Before Fiber, reconciliation was synchronous: once React started diffing, it could not pause until the entire tree was processed. Deep trees caused frame drops. Fiber breaks reconciliation into units of work (fiber nodes), each representing a single element. The reconciler can:
- Pause work to yield to the browser (keeping animations smooth).
- Prioritize urgent updates (user input) over less urgent ones (data fetching results).
- Abort outdated work if new state arrives before the previous reconciliation completes.
Double buffering. React maintains two fiber trees: the current tree (what is on screen) and the workInProgress tree (the next version being built). When reconciliation finishes, React swaps the pointers -- the workInProgress becomes current. This avoids partial UI states.
Vue: compiler-informed Virtual DOM
Vue also uses a Virtual DOM, but its template compiler performs optimizations at build time that dramatically reduce the runtime diffing workload.
Static hoisting. The compiler detects nodes that are entirely static (no dynamic bindings) and hoists their VDOM creation out of the render function. These nodes are created once and reused across every re-render. The renderer skips diffing them entirely when it detects the old and new vnodes are the same reference.
Static node condensation. When multiple consecutive static elements appear, the compiler condenses them into a single "static vnode" containing a plain HTML string, which is set via innerHTML in one operation.
Patch flags. For nodes with dynamic bindings, the compiler attaches numeric patch flags that describe exactly what can change -- class, style, text, props. At runtime, the patching algorithm inspects the flag and jumps directly to the relevant comparison, skipping all attributes that cannot have changed.
Tree flattening. The compiler extracts dynamic nodes into a flat array (block tree), so the runtime only iterates over nodes that actually need diffing, regardless of how deep they sit in the template.
Vue Vapor Mode. Vue's upcoming Vapor Mode goes further: it compiles templates into direct DOM operations with no VDOM at all -- similar to Svelte's approach -- for components that opt in.
Svelte: no Virtual DOM
Rich Harris, Svelte's creator, argued in 2018 that the Virtual DOM is "pure overhead." His thesis: the VDOM is a means to an end (declarative UI), not the only means. If a compiler can analyze component code at build time and generate precise, minimal DOM update instructions, the runtime diffing step is unnecessary.
Svelte is a compiler. It analyzes your component's reactive dependencies at build time and generates imperative JavaScript that directly updates the specific DOM nodes that depend on each piece of state. When count changes, Svelte does not re-render the component or diff a tree; it executes a generated statement like set_data(t, count) that updates a single text node.
Tradeoffs:
- Smaller runtime (no VDOM engine shipped to the browser).
- Updates are O(1) per reactive binding, not O(n) per component tree.
- Less flexibility for highly dynamic UIs where the compiler cannot predict the shape of the output.
- No cross-platform rendering (the compiler targets the DOM specifically).
Solid: signals and direct DOM
Solid.js takes a different path to the same destination. Like React, it uses JSX. Unlike React, it does not use a Virtual DOM. Instead, Solid compiles JSX into real DOM creation code that runs once per component. Reactivity is handled through signals -- observable primitives that track their subscribers at a granular level.
When a signal's value changes, only the specific DOM expressions that read that signal re-execute. The component function itself never re-runs. This is fine-grained reactivity: the reactive graph connects signals directly to DOM update functions, with no intermediate tree representation.
How it differs from React:
- React re-renders components (re-executes the component function) and diffs the resulting trees. Solid runs the component function once and updates only the reactive expressions.
- React's granularity is the component. Solid's granularity is the individual DOM expression.
- React needs
React.memo,useMemo, anduseCallbackto prevent unnecessary work. Solid's reactive system avoids unnecessary work by design.
Design Thinking
Why React invented the Virtual DOM
Before React, building interactive UIs meant writing imperative DOM manipulation: document.getElementById('list').appendChild(newItem). This approach has two fundamental problems:
- It does not scale with complexity. As the number of possible states grows, the number of imperative transitions between states grows combinatorially. A declarative model -- "here is what the UI should look like given this state" -- eliminates transition logic entirely.
- It couples rendering to the DOM. Imperative code targets
documentandelementAPIs directly, making it impossible to render to other targets (server HTML strings, native mobile views, test harnesses).
The VDOM solved both problems. It provided a declarative programming model (describe the UI as a function of state) and a platform-agnostic rendering target (the VDOM is just objects; any renderer can consume them). React Native, React PDF, React Three Fiber, and server-side rendering all exist because the VDOM abstraction separates "what to render" from "where to render it."
Why Svelte and Solid rejected the Virtual DOM
The VDOM introduces overhead: creating a new tree of objects, walking both trees to find differences, and then applying patches. For many applications, this overhead is small and the developer experience benefit is worth it. But it is not zero, and it is proportional to the size of the component tree, not the size of the actual change.
Svelte's insight: if the framework is a compiler rather than a runtime library, it can analyze the code ahead of time and generate update functions that target only the DOM nodes that could possibly change. No tree creation, no diffing, no patching -- just direct assignments.
Solid's insight: if reactivity is built into the primitive layer (signals, effects, memos), the reactive graph itself tracks which DOM nodes depend on which state. When state changes, the graph tells the runtime exactly what to update. No component re-execution, no tree diffing.
The compiler vs. runtime tradeoff
| Runtime VDOM (React) | Compiler-informed VDOM (Vue) | No VDOM -- compiler (Svelte) | No VDOM -- signals (Solid) | |
|---|---|---|---|---|
| Update granularity | Component | Component (with flag shortcuts) | Per binding | Per signal subscriber |
| Bundle includes | VDOM runtime + reconciler | VDOM runtime (smaller) + compiler output | Minimal runtime + generated code | Small runtime + compiled JSX |
| Cross-platform | Yes (React Native, etc.) | Limited (Vapor targets DOM only) | No (DOM only) | Limited |
| Dynamic UI flexibility | High | High | Moderate | High |
| Optimization burden on developer | High (memo, useMemo, useCallback) | Low (compiler handles most) | Very low | Very low |
There is no universally "best" approach. React's VDOM enables an ecosystem of renderers and a mental model that scales to massive teams. Vue's compiler-informed VDOM gets most of the runtime benefit with less developer effort. Svelte and Solid achieve the highest raw update performance by eliminating the VDOM layer entirely, at the cost of cross-platform flexibility.
Best Practices
Always provide stable key props on list items. MUST derive keys from the data's own identity -- a database ID, a UUID, a slug -- never from the array index when the list can be reordered, filtered, or have items inserted or removed. A missing or index-based key causes React to reuse DOM nodes for the wrong data, corrupting input state, breaking animations, and forcing unnecessary DOM mutations. MUST assign the key at the element that React iterates over, not on a child inside it.
Avoid anonymous object and function creation inside render. SHOULD NOT write style={{ color: 'red' }} or onClick={() => handler(id)} inline in JSX when those expressions are props passed to memoized children. Each render creates a new reference, causing React.memo and PureComponent comparisons to always fail, which negates memoization. SHOULD stabilize references with useMemo for objects and arrays, useCallback for functions, or reach for the React Compiler (React 19+) which automates this.
Colocate state to minimize the re-render subtree size. SHOULD lift state only as high as the components that genuinely need it. State at the root causes the entire tree to re-render on every change. SHOULD split frequently-changing state into a context that only the consumers subscribe to, or use a dedicated state library with selector-based subscriptions, so that an update to one piece of state does not cascade through unrelated subtrees.
Visual
Reconciliation: Old Tree to DOM Patches
Framework Approaches Compared
Example
1. React: Key Usage in Lists
Keys are how React identifies which items in a list have changed, been added, or been removed. Without stable keys, React falls back to index-based comparison and may produce incorrect results when items are reordered.
// WRONG: Using array index as key for a reorderable list
function TodoList({ todos, onRemove }) {
return (
<ul>
{todos.map((todo, index) => (
// If items are reordered or removed, index shifts and
// React reuses DOM nodes incorrectly -- input state bleeds
// between items, animations break, performance degrades.
<li key={index}>
<input type="checkbox" />
<span>{todo.text}</span>
<button onClick={() => onRemove(todo.id)}>Remove</button>
</li>
))}
</ul>
);
}
// CORRECT: Using stable, unique ID as key
function TodoList({ todos, onRemove }) {
return (
<ul>
{todos.map((todo) => (
// Stable key lets React track each item across renders.
// Reordering moves DOM nodes instead of recreating them.
<li key={todo.id}>
<input type="checkbox" />
<span>{todo.text}</span>
<button onClick={() => onRemove(todo.id)}>Remove</button>
</li>
))}
</ul>
);
}2. Vue: Static Hoisting and Patch Flags
Vue's template compiler detects static content at build time and generates optimized render code. The developer writes normal templates; the compiler does the optimization work.
<template>
<!-- Static content: hoisted out of the render function, created once -->
<header>
<h1>My Application</h1>
<p>Welcome to the dashboard</p>
</header>
<!-- Dynamic content: only the text binding is diffed -->
<div>
<span>Count: {{ count }}</span> <!-- patch flag: TEXT -->
<button :class="btnClass">Click</button> <!-- patch flag: CLASS -->
</div>
</template>The compiler output conceptually looks like:
// Static nodes are hoisted -- created once, never diffed
const _hoisted_1 = /*#__PURE__*/ createStaticVNode(
'<header><h1>My Application</h1><p>Welcome to the dashboard</p></header>'
);
function render(_ctx) {
return (
openBlock(),
createElementBlock(Fragment, null, [
_hoisted_1, // reused by reference -- diff skipped entirely
createElementVNode("div", null, [
createElementVNode(
"span",
null,
"Count: " + toDisplayString(_ctx.count),
1 /* TEXT -- only text content is diffed */
),
createElementVNode(
"button",
{ class: normalizeClass(_ctx.btnClass) },
"Click",
2 /* CLASS -- only class attribute is diffed */
),
]),
])
);
}3. Solid: Fine-Grained Signal Updates
In Solid, the component function runs once. Signals create reactive subscriptions that update the DOM directly -- no re-render, no diff.
import { createSignal } from "solid-js";
function Counter() {
const [count, setCount] = createSignal(0);
// This console.log runs ONCE when the component mounts.
// In React, it would run on every re-render.
console.log("Counter component function executed");
return (
<div>
{/* Only this text node updates when count changes.
The div, button, and other nodes are never touched. */}
<p>Count: {count()}</p>
<button onClick={() => setCount(count() + 1)}>
Increment
</button>
</div>
);
}When setCount is called, Solid does not re-run the Counter function. It updates only the text node inside the <p> element -- the specific DOM node that subscribed to the count signal. The <div>, the <button>, and every other node remain untouched.
Deep Dive: The Key Reconciliation Algorithm and Why Index Keys Break
React's reconciliation algorithm makes a specific decision at each node in the VDOM tree: if the element type is the same as the previous render, update the existing DOM node in place; if the type has changed, unmount the entire old subtree and mount a fresh one. This decision is cheap and O(n) because React never tries to morph a <div> into a <span> -- it simply destroys and rebuilds.
When React encounters a list (an array of children), it applies the same rule per child, but now it needs to decide which old child corresponds to which new child. Without keys, React compares by position: the child at index 0 in the new array is assumed to be the same as the child at index 0 in the old array. This heuristic is correct only if the list never changes order and never has items inserted or removed from the middle.
Why index keys break on reorder. Consider a list of three items: [A, B, C] rendered with key={index} as keys 0, 1, 2. If the user reverses the list to [C, B, A], React sees keys 0, 1, 2 again. It concludes that the item at key 0 is the same item as before -- just with updated props -- and performs an in-place update. The DOM node at position 0 is not moved; only its content is patched. This means:
- Component state is pinned to the position, not the data. If the item at key 0 had an input element with text typed into it, that text now appears in the slot that was previously occupied by A but now displays C's data. The DOM node stayed, but the data it displays changed.
- Animations cannot run correctly. An animation tied to a component instance (such as a mount/enter transition) never fires, because React never unmounts and remounts the node -- it patches it.
- React.memo and PureComponent memoization fail. Every item appears to have changed (its props changed), so memoization skips the bail-out for every element, defeating the optimization.
Why stable ID keys work. With key={item.id}, React matches old and new children by identity, not by position. When the list is reordered, React recognizes that the DOM node for item A should move to its new position rather than be updated in-place. It performs DOM insertions and moves instead of prop patches, preserving component state, triggering correct lifecycle methods, and allowing CSS transitions to fire.
The same-type / different-type decision without keys. Even outside lists, the same-type heuristic determines whether a component retains its state. A toggle that swaps between <TextInput /> and <NumberInput /> in the same position will unmount and remount the component (losing state) because the types differ. A toggle that swaps between two <TextInput /> components at the same position will update in-place (preserving state), which may be surprising if you expected a fresh component. Using key explicitly on components at the same position is the standard way to force React to treat them as distinct instances and reset state on change.
Common Mistakes
1. Treating the Virtual DOM as a performance guarantee
The VDOM is not a performance optimization -- it is a programming model optimization. It exists so developers can write declarative UI code without manually tracking DOM mutations. The VDOM adds overhead (tree creation, diffing, patching) compared to perfectly targeted imperative code. It is faster than naive "blow away and rebuild the entire DOM" approaches, but slower than surgically precise manual updates.
Fix: Understand the VDOM as a tradeoff: developer experience and correctness in exchange for some runtime cost. When that cost matters, use framework-specific tools to reduce it (React.memo, Vue patch flags, etc.) or consider frameworks that skip the VDOM entirely.
2. Not using framework-specific optimizations
Each framework provides tools to short-circuit unnecessary work, but developers often ignore them:
- React:
React.memoto skip re-rendering when props have not changed.useMemoanduseCallbackto stabilize references. React Compiler (React 19+) automates these. - Vue:
v-onceto render a subtree only once and never update it.v-memoto memoize parts of a template based on dependency values.shallowRefandshallowReactiveto opt out of deep reactivity. - Svelte:
{#key}blocks to force re-creation when a value changes. Immutable data patterns to help the compiler optimize.
Fix: Learn and apply the performance primitives of your chosen framework. Profile first, optimize second.
Related FEEs
| FEE | Relationship |
|---|---|
| FEE-700 Rendering & Performance Overview | Parent overview covering the browser rendering pipeline. The VDOM reconciliation process produces DOM mutations that then flow through the browser's style, layout, paint, and composite stages. |
| FEE-401 DOM APIs & Traversal | The real DOM APIs that VDOM frameworks abstract over. Understanding the cost of createElement, setAttribute, and appendChild explains why batching via a VDOM (or compiler/signals) matters. |
| FEE-502 Reactive State Primitives | Signals, observables, and reactive primitives are the foundation of Solid's and Vue's fine-grained reactivity -- the mechanism that makes VDOM-less updates possible. |
| FEE-601 Local Component State | Component state triggers re-renders in VDOM frameworks. Understanding how useState, ref, and $state work is essential for understanding when reconciliation runs. |
References
- Reconciliation -- React (Legacy Docs) -- React's official explanation of the diffing algorithm, the two heuristics (element type and keys), and why O(n) is achievable
- React Fiber Architecture -- Andrew Clark -- The original design document for React Fiber, explaining incremental rendering, prioritization, and the fiber data structure
- Rendering Mechanism -- Vue.js -- Vue's official documentation on its compiler-informed VDOM, static hoisting, patch flags, and tree flattening
- Virtual DOM is Pure Overhead -- Rich Harris (Svelte Blog) -- The influential 2018 essay arguing that the VDOM is a means to declarative UI, not the only means, and that compilers can do better
- Fine-Grained Reactivity -- Solid Docs -- Solid's documentation on how signals, effects, and memos create a reactive graph that updates the DOM without a VDOM
- Thinking Granular: How is SolidJS so Performant? -- Ryan Carniato -- Deep dive into Solid's compilation model and why fine-grained reactivity outperforms VDOM diffing for most update patterns