virtual-dom is a JavaScript DOM model supporting efficient declarative re-rendering through diff and patch operations.
Setup & Imports
const h = require('virtual-dom/h');
const diff = require('virtual-dom/diff');
const patch = require('virtual-dom/patch');
const createElement = require('virtual-dom/create-element');
Initial Rendering
// 1: Create a virtual tree using hyperscript
const tree = h('div', { style: { color: 'blue' } }, ['Hello World']);
// 2: Create a real DOM element node from the virtual tree
const rootNode = createElement(tree);
// 3: Append to document body
document.body.appendChild(rootNode);
Updating & Patching
// 4: Create a second updated virtual tree
const newTree = h('div', { style: { color: 'red' } }, ['Hello Updated World']);
// 5: Calculate the diff delta between old and new trees
const patches = diff(tree, newTree);
// 6: Patch the real DOM node in-place
patch(rootNode, patches);