Virtual DOM and patch: The Core of Rendering Updates

Understand vnode structure, the main patching flow, and how Vue 3 uses patch flags and Blocks for targeted updates.

🎯 Introduction

We have traced reactive updates: reactive intercepts reads and writes, effect tracks dependencies, and the scheduler queues component jobs for asynchronous execution. One link remains: when an update runs, how does a component's vnode become real DOM?

This article completes that link. By the end, you will be able to:

  • Explain what a vnode is and how it relates to real DOM.
  • Follow render and patch: mount when no old vnode exists, update otherwise.
  • Describe how patch dispatches by node type and compares element props and children.
  • Explain how Vue 3 flags dynamic content and collects dynamic nodes in Blocks to skip static content during optimized updates.

The excerpts use Vue 3.5.x from the GitHub vuejs/core repository, primarily packages/runtime-core/src/vnode.ts and packages/runtime-core/src/renderer.ts. Standalone examples can run with Node.js v22.


🧱 What Is a VNode?

If browsers only display real DOM, why introduce virtual DOM?

A vnode, or virtual node, is an ordinary JavaScript object describing a UI node. It is virtual because it exists in JavaScript rather than as a browser DOM node. Think of it as a blueprint recording the node's type, properties, and content. Vue uses that blueprint to create and update the real DOM, making the vnode a lightweight representation of it.

The h function creates vnodes. Templates also compile to vnode-creation calls. Here are the essential fields extracted from the source:

// Simplified from packages/runtime-core/src/vnode.ts
function createVNode(type, props = null, children = null) {
    const vnode = {
        // 'div' represents an element, Text a text node, and an object a component
        type,
        // Properties such as id, class, and event listeners
        props,
        // A string or an array of child vnodes
        children,
        // Reference to the real DOM node, populated after rendering
        el: null,
        // Compiler-generated dynamic-content flag, explained below
        patchFlag: 0,
        // Identity used when comparing nodes
        key: props && props.key,
    };
    return vnode;
}

For example, createVNode('div', { id: 'app' }, 'hello') describes <div id="app">hello</div>. Remember three points:

  • type identifies the node kind. Strings represent native elements; Symbols such as Text and Fragment represent special built-in nodes; objects can represent components.
  • el connects the vnode to the real DOM. After rendering, updates can use vnode.el to modify the existing node directly.
  • Creating vnodes is inexpensive. It allocates ordinary objects rather than directly manipulating DOM. This is what makes the representation lightweight.

🧱 The Main render and patch Flow

How does a vnode become real DOM? First, two recurring terms: mounting creates DOM from a vnode and inserts it for the first time; unmounting removes the rendered DOM.

The renderer is the set of functions that turns vnodes into output. Its render function is the entry point:

// Simplified from packages/runtime-core/src/renderer.ts
function render(vnode, container) {
    if (vnode == null) {
        // No new vnode: unmount the previous rendered content
        if (container._vnode) {
            unmount(container._vnode);
        }
    } else {
        // Compare the previous vnode with the new one
        patch(container._vnode, vnode, container);
    }
    // Save this vnode as the old vnode for the next update
    container._vnode = vnode;
}

For a new vnode, there are two paths:

  • No old vnode (container._vnode is null): perform the initial mount, creating DOM from scratch.
  • An old vnode exists: pass both to patch for a comparison and update, changing the necessary parts.

Component updates follow the second path: the render effect produces a new vnode, then calls patch(oldVNode, newVNode). Patching performs the actual update work.

_vnode is a field Vue adds to the container to remember the previous render. Without it, the next update would have no old vnode to compare.

🧱 How patch Dispatches Work

What happens first after patch receives the two vnodes? Check their identity, then dispatch by node type.

// Simplified from packages/runtime-core/src/renderer.ts
// Matching identity requires both the same type and the same key
function isSameVNodeType(n1, n2) {
    return n1.type === n2.type && n1.key === n2.key;
}

If a div becomes a p, or its key changes, Vue unmounts the old node and mounts the new one instead of comparing incompatible nodes. This also explains the importance of keys in v-for, discussed in the questions below. Next, patch dispatches by type:

// Simplified from packages/runtime-core/src/renderer.ts
function patch(n1, n2, container) {
    // Replace an old node with a different identity
    if (n1 && !isSameVNodeType(n1, n2)) {
        unmount(n1);
        n1 = null; // Treat the remaining work as a fresh mount
    }

    const { type } = n2;

    if (type === Text) {
        // Text node
        processText(n1, n2, container);
    } else if (typeof type === 'string') {
        // Native element, such as div or span
        processElement(n1, n2, container);
    } else if (typeof type === 'object') {
        // Component
        processComponent(n1, n2, container);
    }
}

Let's focus on the common element case. It chooses between mounting and updating; updates compare props and children:

// Simplified from packages/runtime-core/src/renderer.ts
function processElement(n1, n2, container) {
    if (n1 == null) {
        // No old node: create and insert DOM
        mountElement(n2, container);
    } else {
        // Existing node: compare and update
        patchElement(n1, n2);
    }
}

function patchElement(n1, n2) {
    // Reuse the existing DOM element
    const el = (n2.el = n1.el);

    // 1. Compare props, including class, style, and events
    patchProps(el, n1.props, n2.props);

    // 2. Compare children
    patchChildren(n1, n2, el);
}

The guiding principle is reuse real DOM where possible and change only what is necessary. patchChildren also dispatches by child shape: text can be updated directly, while two arrays enter a diffing process to determine the required changes.


🧱 Diffing and Compiler Optimizations

Comparing arrays of children can require visiting many nodes. How can Vue 3 avoid comparing everything?

It moves analysis to compile time, when templates are translated into render functions before execution. Runtime is when those functions execute. Vue 3 determines which template content may change and records that information in the generated vnode code. The renderer uses it to guide updates. Two mechanisms work together.

Optimization 1: Patch Flags Identify Dynamic Content

The compiler identifies static content, dynamic content, and the kinds of changes each dynamic node may need. It records the result as a numeric patchFlag:

// Simplified from packages/shared/src/patchFlags.ts
const PatchFlags = {
    TEXT: 1, // Dynamic text content
    CLASS: 2, // Dynamic class
    STYLE: 4, // Dynamic style
    PROPS: 8, // Dynamic properties
    // ... Other flags are omitted
};

For example:

<div>
    <p>Static content that never changes</p>
    <p :class="cls">{{ msg }}</p>
</div>

The second p receives TEXT | CLASS, whose value is 1 | 2 = 3. During an update, patch knows to check text and class rather than unrelated properties and listeners.

Optimization 2: Blocks Collect Dynamic Nodes

Knowing which parts of one node are dynamic is not enough if the renderer still has to search a large static tree to find it. Vue 3 uses Blocks to collect dynamic descendants into a flat dynamicChildren list on a block root, guided by compiler-generated code:

// Conceptual result of compiled rendering; not runnable code
const block = {
    type: 'div',
    children: [
        /* One hundred static nodes and one dynamic node */
    ],
    // Updates can traverse this separate dynamic-node list directly
    dynamicChildren: [dynamicParagraphVNode],
};

For an optimized update of this tree, the renderer visits the dynamicChildren list and skips static content. Even with a hundred static nodes, the relevant traversal cost depends on the dynamic nodes.

Instead of checking every node for changes, the compiler-guided renderer has a list of nodes to visit. This makes the optimized update work depend on dynamic content rather than the amount of surrounding static content.

The compiler emits patch flags and Block-related calls; the runtime uses them to collect and update dynamic nodes. Templates receive these optimizations automatically, while ordinary handwritten render functions do not. The next article explains compilation in detail.

⚡ Comparing Patching with Vue 2

Compare this with the Vue 2 source code course:

  • Vue 2 compares old and new child arrays at runtime with a double-ended diff. Without Vue 3's patch flags and Block metadata, it generally has more tree traversal to perform, including checks around static content.
  • Vue 3 analyzes static and dynamic structure ahead of time, uses patch flags to identify change types, and uses Blocks to collect dynamic nodes. The runtime performs targeted updates, skipping static subtrees on optimized paths.

The central performance idea is move available work to compile time so the runtime does less work, rather than relying only on a faster diff algorithm.

When child structure is fully dynamic, such as a list generated by a handwritten render function, the compiler cannot predict it. Vue 3 still needs array diffing. The Snabbdom course covers array comparison, keys, and the longest increasing subsequence. An overview is sufficient here.

❓ Questions and Answers

Q1: If the browser still needs real DOM operations, what does virtual DOM add?

Two benefits are separating description from rendering and making differences easier to compute. An object-based description can target browsers, native renderers, or test snapshots. Comparing JavaScript descriptions also lets the renderer determine the necessary DOM changes without repeatedly inspecting the real DOM. Compiler optimizations further narrow the expensive work.

Q2: Are patch flags generated at runtime or compile time?

At compile time. The template compiler emits flags and Block-related structure in render function code. The runtime consumes them to choose an update strategy. Handwritten render functions do not automatically receive this analysis. The next article shows how compilation produces it.

Q3: Why are keys important in v-for?

Patching and diffing use keys, together with node types, to identify corresponding vnodes. Stable unique keys let Vue recognize moved nodes and preserve the correct DOM and component state. Index keys can identify the wrong item after reordering, causing issues such as mismatched input values or state.

Q4: What happens when two vnodes have different types?

When isSameVNodeType finds a different type or key, Vue unmounts the old node and mounts the new one. It does not try to preserve an incompatible node, since cross-type reuse would complicate the comparison and can cost more than replacement.

Q5: Is ordinary diffing still needed after Block optimization?

Yes. Blocks optimize common templates with known static and dynamic structure. Fully dynamic child arrays still need array diffing, using keys and comparison strategies to minimize moves.


🧪 Exercise

Without looking up the implementation, write a mini h(type, props, children) that returns a vnode with at least type, props, children, and key. Use it to describe a two-level UI tree and print it. Save as a .js file and run with Node.js v22.

function h(type, props, children) {
    // Your code here
}

// Describe <div id="app"><p class="msg">hello</p></div> with h
const vnode = h('div', { id: 'app' }, [
    // Your code here: create the p vnode
]);

console.log(JSON.stringify(vnode, null, 2));

For an extra challenge, add a patchFlag field: use 1 for string children and 0 otherwise. In real Vue, at which stage is dynamic content identified?


🎉 You now understand virtual DOM and the main patching flow! We have repeatedly referred to compiler-generated flags and Blocks. Next, we will follow template compilation to see how templates become render functions carrying those optimization hints.