Practice: Build a miniature virtual DOM
🎯 Introduction
In this final project, we will build a miniature version of Snabbdom. We will divide it into five small steps, each requiring only a handful of lines. Run the code after each step to see the result immediately. By the end, the virtual DOM will no longer be a black box.
🧱 Goals and design
First, meet the four parts we will implement:
| Part | Responsibility | Analogy |
|---|---|---|
h | Package a description into a virtual node object | Draw the blueprint |
createElm | Turn a virtual node into real DOM | Build from the blueprint |
sameVnode | Check whether two nodes have the same identity | Check the address |
patch | Handle initial rendering and updates | Coordinate the work |
To focus on the essentials, we will make two simplifications: selectors support only plain tag names, without parsing #id or .class; child updates clear and rebuild the content instead of diffing it in detail.
Create mini-vdom.js in your project to get started.
🛠 Step 1: h (about 8 lines)
h does one thing: package the description you provide into an object.
// Create a virtual node: supports only h(sel, data, text) and h(sel, data, [children]).
export function h(sel, data, params) {
if (typeof params === 'string') {
// h(sel, data, text)
return { sel, data, text: params };
}
// h(sel, data, [children])
return { sel, data, children: params };
}
Compare this with article 2. The returned object's sel, text, and children fields are already familiar; nothing new is required.
🛠 Step 2: createElm (about 15 lines)
createElm turns an object into real DOM in three steps: create the element, store its reference, and handle its content.
// Turn a virtual node into real DOM.
function createElm(vnode) {
const elm = document.createElement(vnode.sel);
vnode.elm = elm; // Store the corresponding real element.
if (vnode.text !== undefined) {
elm.textContent = vnode.text;
} else if (vnode.children) {
for (const child of vnode.children) {
elm.appendChild(createElm(child)); // Process children with the same function.
}
}
return elm;
}
The crucial line is vnode.elm = elm. It establishes the correspondence between virtual nodes and real DOM discussed in article 2. createElm processes children recursively, so it supports nesting at any depth.
🛠 Step 3: the first patch version (initial rendering only, 6 lines)
Start with a patch function that only handles the initial render so we can get the page working immediately:
// Rendering (first version: initial render only)
export function patch(oldVnode, newVnode) {
const elm = createElm(newVnode);
oldVnode.parentNode.replaceChild(elm, oldVnode);
return newVnode;
}
These three lines put article 4 into practice: replaceChild replaces the container itself with the element generated from the vnode.
Test it now. Add this to main.js:
import { h, patch } from './mini-vdom.js';
const vnode = h('div', {}, [
h('h2', {}, 'Miniature virtual DOM'),
h('p', {}, 'A page rendered by our own code')
]);
patch(document.getElementById('app'), vnode);
Open the browser. The heading and paragraph appear: our virtual DOM can now render a page!
🛠 Step 4: add updates to patch
The current patch fails on updates because the old vnode is not a container element. Add a node identity check and an update branch:
// Check whether two nodes have the same identity.
function sameVnode(a, b) {
return a.sel === b.sel && a.data.key === b.data.key;
}
// Rendering and updates (complete version)
export function patch(oldVnode, newVnode) {
// Initial render: oldVnode is the container.
if (oldVnode.sel === undefined) {
const elm = createElm(newVnode);
oldVnode.parentNode.replaceChild(elm, oldVnode);
return newVnode;
}
if (sameVnode(oldVnode, newVnode)) {
// Same node: reuse the element and update only its content.
newVnode.elm = oldVnode.elm;
if (newVnode.text !== undefined) {
newVnode.elm.textContent = newVnode.text;
} else {
// Simplification: clear and rebuild children.
newVnode.elm.innerHTML = '';
for (const child of newVnode.children) {
newVnode.elm.appendChild(createElm(child));
}
}
} else {
// Different nodes: replace the element.
const elm = createElm(newVnode);
oldVnode.elm.parentNode.replaceChild(elm, oldVnode.elm);
}
return newVnode;
}
This code directly implements the diffing rules from article 6: check sameVnode, overwrite text content, and replace elements when nodes differ.
Test again. Replace main.js with:
import { h, patch } from './mini-vdom.js';
let vnode = h('p', {}, 'I will change in 2 seconds');
vnode = patch(document.getElementById('app'), vnode);
setTimeout(() => {
vnode = patch(vnode, h('p', {}, 'I changed!'));
}, 2000);
Refresh the page. The text changes automatically after 2 seconds: updates now work too.
🛠 Step 5: add event binding (4 lines)
Finally, extend createElm to recognize on in data and bind events. Add this immediately below vnode.elm = elm;:
// Bind events.
if (vnode.data.on) {
for (const name in vnode.data.on) {
elm.addEventListener(name, vnode.data.on[name]);
}
}
Final test: a counter. Replace main.js with:
import { h, patch } from './mini-vdom.js';
let count = 0;
let vnode = render();
function render() {
return h('div', {}, [
h('p', {}, 'Current count: ' + count),
h('button', { on: { click: add } }, 'Click to add 1')
]);
}
function add() {
count++;
vnode = patch(vnode, render()); // State changes → new blueprint → compare and update.
}
vnode = patch(document.getElementById('app'), vnode);
Click the button, and the count increases. We have recreated the core virtual DOM workflow: state → virtual node tree → patch → real DOM. This cycle also underlies Vue's data-driven rendering.
⚖️ How this differs from real Snabbdom
Our miniature implementation is a teaching skeleton. Real Snabbdom also provides:
- Selector parsing for
#idand.class, and SVG namespace handling. - A module system for classes, styles, properties, events, and more.
- Detailed double-ended comparison in
updateChildren, reusing and moving children by key instead of clearing and rebuilding them. - Complete lifecycle hooks and support for removal animations.
The value of this miniature implementation is that its core ideas match the real implementation. The remaining features build on that foundation.
❓ Questions and answers
Q1: Why assign patch's return value back to vnode?
The next update must use the most recent virtual node as its old tree. Assigning the result back to vnode gives the next patch the correct comparison baseline.
Q2: Does clearing and rebuilding children also remove their event listeners?
The old elements and their listeners are discarded, and createElm binds listeners on the new elements, so behavior still works. Rebuilding wastes work, which is why real Snabbdom uses keys to reuse elements precisely.
Q3: Will reading a.data.key in sameVnode throw if data has no key?
No. Reading a missing property on an object returns undefined. Two undefined values compare equal, as intended.
Q4: Can this miniature implementation be used in production?
No. It lacks modules and detailed diffing and is intended only for learning. Use Snabbdom or an established framework in real projects.
🧪 Exercise
Extend h to support the shorthand h(sel, text), passing a string as the second argument without a data object. Verify rendering with h('p', 'Shorthand text').
export function h(sel, data, params) {
// Write your code here. Hint: first check whether the second argument is a string.
}
🎉 You have completed the Snabbdom course! From the virtual DOM concept through h, modules, patch, keys, and diffing to building your own miniature virtual DOM, you now understand how the pieces fit together. This foundation will help you read Vue's source code and optimize rendering performance.
