virtual-dom は、diff(差分計算)と patch(最小更新)により高速な宣言的 UI 再描画を実現する JavaScript 仮想 DOM ライブラリです。
セットアップとモジュール読み込み
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');
初回レンダリングと実 DOM 生成
// 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);
差分計算と DOM 反映(Diff & Patch)
// 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);