The patch function: Rendering and updates

Learn the two forms of patch, how initial rendering replaces the container, and the two update paths, and avoid reusing the original container.

🎯 Introduction

If h draws the blueprint, patch does the building. In this article, we will explore its two forms, how the container is replaced on the initial render, and a common beginner mistake.


🧱 Two ways to call patch

patch takes two arguments. Its behavior depends on the first argument:

main.js
// Form 1: patch(realDOMElement, vnode) — initial render
patch(document.getElementById('app'), vnode);

// Form 2: patch(oldVnode, newVnode) — update
patch(vnode, newVnode);
ScenarioFirst argumentSecond argumentBehavior
Initial renderReal DOM element (container)Virtual nodeCreate and mount a real element
UpdateOld virtual nodeNew virtual nodeCompare differences and minimize updates

⚠️ Initial rendering replaces the container

An important detail: patch replaces the container itself with the element generated from the vnode, rather than inserting that element inside the container.

main.js
// The original HTML contains <div id="app"></div>.
const vnode = h('p', 'First paragraph');
patch(document.getElementById('app'), vnode);

After rendering, the page structure is:

<p>First paragraph</p>

The original <div id="app"> is no longer on the page! The following code is therefore incorrect:

main.js
// ❌ Incorrect: look up the original container again for the second patch.
patch(document.getElementById('app'), newVnode);

At this point, document.getElementById('app') returns null, causing an error.

Saving the container element in a variable and reusing it does not work either. The container has already been replaced, so patching it will not update the page. This silent failure can be difficult to diagnose.

Always save the vnode returned by patch and use it for the next update:

main.js
// ✅ Correct approach
let vnode = h('p', 'First paragraph');
vnode = patch(document.getElementById('app'), vnode); // Save the returned vnode.

const newVnode = h('p', 'Second paragraph');
vnode = patch(vnode, newVnode); // Update using the old vnode.

patch returns the new virtual node. Saving it establishes the update cycle: old vnode → patch → new vnode → patch again.


⚙️ Two update paths

When you call patch(oldVnode, newVnode), Snabbdom first checks whether the nodes are the same: their selectors and keys must match, as article 6 explains in detail.

Case 1: Same node → update in place. Reuse the real element and change only what differs:

main.js
let vnode = h('div', 'Before the update');
vnode = patch(document.getElementById('app'), vnode);

// Same sel: reuse the real div and update only its text.
vnode = patch(vnode, h('div', 'After the update'));

Case 2: Different nodes → replace the element. Remove the old element and create a new one:

main.js
// Changing div to p changes sel, so the entire element is replaced.
vnode = patch(vnode, h('p', 'A new element'));

Remember: keep sel stable where possible so Snabbdom can update in place for the best performance.


🪝 Introduction to hooks

Modules participate in rendering through hooks. Snabbdom provides a full set of lifecycle hooks, including these common ones:

HookWhen it runs
createAfter the real element is created
insertAfter the element is inserted into the page
updateWhen the node is updated
destroyWhen the element is removed

For example, use insert to focus an input after rendering:

main.js
const vnode = h('input', {
    hook: {
        insert: (vn) => vn.elm.focus()
    }
});
patch(document.getElementById('app'), vnode);

The hook callback receives the virtual node vn. Use vn.elm to access the real element. Hooks may not be needed often in everyday development, but they are useful for tasks that require direct DOM access, such as animations and automatic focus.


❓ Questions and answers

Q1: Why replace the container instead of inserting content into it?

This keeps each vnode in a one-to-one relationship with a real element, making subsequent updates simpler and more consistent. Vue 2 follows the same design when replacing #app during mounting.

Q2: Can I ignore the return value of patch?

The syntax allows it, but you lose the update chain. Make vnode = patch(...) a habit.

Q3: Is it safe to call patch repeatedly?

Yes. Each call compares against the previous result. This is how data-driven interfaces work: when data changes, create a new vnode and patch again.

Q4: How can I clear all rendered content?

Patch with a comment node: patch(vnode, h('!')). h('!') creates a comment node that replaces the previous content.


🧪 Exercise

Make a paragraph change in stages. First render a p containing "I am a paragraph". After 2 seconds, update it to a p containing "Still a paragraph" and observe element reuse. After another 2 seconds, update it to an h2 heading and observe replacement. Watch the changes in the Elements panel of your browser's developer tools.

main.js
import { init, h } from 'snabbdom';

const patch = init([]);

// Write your code here. Hint: schedule patch calls with setTimeout.

🎉 You now understand the patch process! Next, we will explore keys, which play an essential role in rendering lists.