Virtual DOM and patch: From VNodes to Real DOM

Explore the VNode structure, the patching process, and Vue 2's double-ended diffing strategy.

🎯 Introduction

A compiled render function produces a VNode tree, but VNodes are ordinary JavaScript objects that browsers cannot display directly. One step remains: creating real DOM and updating it efficiently when data changes. That step is patching.

By the end of this article, you will understand the VNode structure, how patch handles initial rendering and updates, and the four comparisons in double-ended diffing.


🧱 Prerequisites

Vue 2's virtual DOM implementation draws on Snabbdom, including its VNode structure, patching flow, and double-ended diffing strategy. If these are unfamiliar, start with the Snabbdom course. Concepts such as h, patch, and pointers at both ends of a list appear directly in this article.

Here, we revisit those concepts through the Vue 2 source (vue@2.7.16), focusing on their implementation rather than repeating the underlying explanations.


🧱 VNode: Describe DOM with JavaScript Objects

A VNode (virtual node) is an ordinary JavaScript object whose fields describe a DOM node. Its source definition is in src/core/vdom/vnode.js. Here are its simplified core fields:

// Simplified from src/core/vdom/vnode.js
export default class VNode {
    constructor(tag, data, children, text, elm, key, componentOptions) {
        this.tag = tag // Tag name, such as 'div'; component VNodes use an internal tag
        this.data = data // Data such as attributes, events, and classes
        this.children = children // Array of child VNodes
        this.text = text // Text content for text nodes
        this.elm = elm // Corresponding real DOM element
        this.key = key // Node identity key
        this.componentOptions = componentOptions // Options specific to component VNodes
    }
}

Consider this real DOM:

<div id="app">
    <p>hello</p>
</div>

Its corresponding VNode looks roughly like this:

{
    tag: 'div',
    data: { attrs: { id: 'app' } },
    children: [
        {
            tag: 'p',
            data: undefined,
            children: undefined,
            text: undefined,
            elm: undefined // Assigned the real <p> element after rendering
        }
    ]
}

The elm field connects the VNode to the real DOM. After creating an element, patch stores its reference in elm. Later updates can manipulate the element directly without searching the document.


🧱 _render and _update: From Render Function to patch

Rendering has two steps, implemented by instance methods simplified from src/core/instance/render.js and src/core/instance/lifecycle.js:

// Step 1: execute the render function to produce a VNode tree
Vue.prototype._render = function () {
    const vm = this
    const { render } = vm.$options
    // The render function creates VNodes through $createElement (h)
    const vnode = render.call(vm, vm.$createElement)
    return vnode
}

// Step 2: turn the VNode tree into real DOM
Vue.prototype._update = function (vnode) {
    const vm = this
    const prevVnode = vm._vnode
    vm._vnode = vnode
    if (!prevVnode) {
        // Initial render: oldVnode is the real mount element
        vm.$el = vm.__patch__(vm.$el, vnode)
    } else {
        // Update: oldVnode is the previous VNode tree
        vm.$el = vm.__patch__(prevVnode, vnode)
    }
}

_render() produces a VNode, and _update() calls __patch__ to apply it to the page. Both initial rendering and subsequent updates use __patch__; the first argument differs. That distinction leads to the next section.


🧱 Two Paths Through patch

The entry logic in patch, simplified from src/core/vdom/patch.js, branches according to oldVnode:

// Simplified from src/core/vdom/patch.js
function patch(oldVnode, vnode) {
    if (!oldVnode) {
        // Path 1: no oldVnode, as on a component's initial render
        // Nothing to compare: create the entire DOM tree from vnode
        createElm(vnode)
    } else {
        if (sameVnode(oldVnode, vnode)) {
            // Path 2: matching nodes; compare and update their contents
            patchVnode(oldVnode, vnode)
        } else {
            // Different nodes: create a new element, replace the old one, and destroy it
            const elm = oldVnode.elm
            const parentElm = elm.parentNode
            createElm(vnode, parentElm, elm)
            removeVnodes([oldVnode], 0, 0)
        }
    }
    return vnode.elm
}
  • Initial render: oldVnode is absent or is a mount element to replace. createElm recursively creates the DOM tree and inserts it into the page.
  • Update: both VNode trees exist. sameVnode determines whether to reuse and update the old node or replace it.

⚖️ sameVnode and patchVnode

sameVnode: Do the Nodes Match?

// Simplified from src/core/vdom/patch.js
function sameVnode(a, b) {
    return (
        a.key === b.key &&
        a.tag === b.tag &&
        // Additional checks include comment status and whether data is defined
        isDef(a.data) === isDef(b.data)
    )
}

The main checks are matching keys and tags. The result determines the update path:

  • Match → enter patchVnode, reuse the real element, and update its contents.
  • No match → destroy the old element and create a new one.

patchVnode: Cases for Reusing a Node

Entering patchVnode means the nodes match. The real element (elm) is reused, and its contents are updated. Here are the simplified branches:

// Simplified from src/core/vdom/patch.js
function patchVnode(oldVnode, vnode) {
    const elm = (vnode.elm = oldVnode.elm) // Reuse the real element
    const oldCh = oldVnode.children
    const ch = vnode.children

    if (isDef(vnode.text)) {
        // Case 1: the new node contains text; replace the content
        elm.textContent = vnode.text
    } else if (isDef(oldCh) && isDef(ch)) {
        // Case 2: both nodes have children; use double-ended diffing
        updateChildren(elm, oldCh, ch)
    } else if (isDef(ch)) {
        // Case 3: only the new node has children; clear old text and insert them
        elm.textContent = ''
        addVnodes(elm, null, ch, 0, ch.length - 1)
    } else if (isDef(oldCh)) {
        // The new node is empty; remove all old children
        removeVnodes(oldCh, 0, oldCh.length - 1)
    }
}

These are the same rules as in the Snabbdom course: replace text directly, call updateChildren when both nodes have children, and add or remove children when only one does. Vue 2 handles additional cases such as component nodes, but the underlying approach is the same.


🧠 updateChildren: Four Double-Ended Comparisons

When both nodes have children, Vue calls updateChildren. Like Snabbdom, Vue 2 places start and end pointers on both child arrays and performs four comparisons in a fixed order each iteration.

The comparisons and their actions are:

OrderComparisonMeaning of a matchAction
①Old start vs. new startStart is unchangedCall patchVnode and advance both start pointers
②Old end vs. new endEnd is unchangedCall patchVnode and move both end pointers backward
③Old start vs. new endOld start moved to the endUpdate and move the old start element to the end
④Old end vs. new startOld end moved to the startUpdate and move the old end element to the start

Here is simplified pseudocode. The actual updateChildren in src/core/vdom/patch.js includes additional branches such as key-map lookup:

// Simplified from updateChildren in src/core/vdom/patch.js
function updateChildren(parentElm, oldCh, newCh) {
    let oldStartIdx = 0, oldEndIdx = oldCh.length - 1
    let newStartIdx = 0, newEndIdx = newCh.length - 1

    while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
        if (sameVnode(oldCh[oldStartIdx], newCh[newStartIdx])) {
            // ① Old start vs. new start
            patchVnode(oldCh[oldStartIdx], newCh[newStartIdx])
            oldStartIdx++; newStartIdx++
        } else if (sameVnode(oldCh[oldEndIdx], newCh[newEndIdx])) {
            // ② Old end vs. new end
            patchVnode(oldCh[oldEndIdx], newCh[newEndIdx])
            oldEndIdx--; newEndIdx--
        } else if (sameVnode(oldCh[oldStartIdx], newCh[newEndIdx])) {
            // ③ Old start vs. new end: old start moved to the end
            patchVnode(oldCh[oldStartIdx], newCh[newEndIdx])
            parentElm.insertBefore(oldCh[oldStartIdx].elm, null) // Move to the end
            oldStartIdx++; newEndIdx--
        } else if (sameVnode(oldCh[oldEndIdx], newCh[newStartIdx])) {
            // ④ Old end vs. new start: old end moved to the start
            patchVnode(oldCh[oldEndIdx], newCh[newStartIdx])
            parentElm.insertBefore(oldCh[oldEndIdx].elm, oldCh[oldStartIdx].elm)
            oldEndIdx--; newStartIdx++
        } else {
            // No match: build a key map of old children and look up the new node
            // Reuse and move a matching node, or create one if none exists
        }
    }
    // After the loop: remove remaining old nodes or insert remaining new nodes
}

Remember matching ends first, then crosswise comparisons. Comparisons ① and ② handle common unchanged positions; ③ and ④ handle moves between ends. A key map handles the remaining cases. Pointer movement and keyed lookup take O(1) per step, giving O(n) overall for keyed children.

Understanding the order matters more than memorizing it. Comparing start-to-start and end-to-end first favors common updates that leave the boundaries unchanged, such as appending items or removing an item in the middle, with fewer moves.

🔑 Revisiting key

A key identifies a node. Together with the tag, it determines sameVnode and whether the element can be reused. Stable, unique keys let list diffing reuse and move the correct elements instead of reusing elements by position and rewriting their contents.


❓ Knowledge Check

Q1: Does initial rendering use patch too?

Yes. With no old VNode, or with a mount element to replace, patch uses createElm to create the DOM tree from the VNodes without diffing an existing VNode tree.

Q2: Does a sameVnode match mean the element is reused?

Yes. In patchVnode, the new VNode inherits the old VNode's elm. Attributes and contents are updated without recreating the element.

Q3: What happens if none of the four comparisons match?

Vue builds a key map of old children and looks up the new start node's key. A matching old node can be reused and moved to the correct position; otherwise, a new element is created.

Q4: Why not compare every pair of children with nested loops?

Nested loops take O(n²). Double-ended pointers handle common cases with O(1) pointer operations per step, giving O(n) for keyed lists while reducing real DOM moves.


🧪 Exercise

Suppose a list changes from [A, B, C] to [C, A, B], with li keys a, b, and c. Use comments to trace the comparisons without implementing the algorithm: which comparison matches each round, how the pointers move, and which DOM operations occur.

// Old children: [A(key:a), B(key:b), C(key:c)]
// New children: [C(key:c), A(key:a), B(key:b)]
//
// Round 1: comparison ___ matches (hint: compare starts first, then ends)
// Write your answer here: describe the match and pointer movements
//
// Round 2:
// Write your answer here
//
// Final DOM operation count:
// Write your answer here: how many elements moved? Were any created or removed?

🎉 You now understand Vue 2's virtual DOM and patching flow! VNodes describe the view, patch applies it, and double-ended diffing updates it efficiently. Together, they form the core rendering path.