Virtual DOM — Explained with Examples
The virtual DOM is a lightweight JavaScript representation of the real DOM, enabling efficient UI updates through batching and diffing.
The virtual DOM is an in-memory tree of plain JavaScript objects that mirrors the real DOM. When state changes, frameworks like React or Vue build a new virtual DOM tree, diff it against the previous one (reconciliation), compute the minimal set of changes, and apply those changes to the real DOM in a single batch. This avoids expensive direct DOM manipulations.
Think of the virtual DOM like a drafts folder for a document. Instead of printing a new copy of the entire 100-page report every time you fix a typo (direct DOM manipulation), you make changes in your drafts folder (virtual DOM), print only the pages that changed (diffing), and replace those pages in the binder (batch update).
React popularized the virtual DOM pattern, but Vue, Preact, and other frameworks use similar approaches. The key insight is that JavaScript object operations are cheaper than real DOM operations.
// Simplified virtual DOM representation
const vdom = {
type: 'div',
props: { className: 'container' },
children: [
{
type: 'h1',
props: {},
children: ['Hello, World!']
},
{
type: 'p',
props: {},
children: ['This is virtual DOM']
}
]
};
// Diffing (simplified)
function diff(oldVNode, newVNode) {
const patches = [];
if (oldVNode.type !== newVNode.type) {
patches.push({ type: 'REPLACE', newNode: newVNode });
} else if (oldVNode.children !== newVNode.children) {
patches.push({ type: 'UPDATE', children: newVNode.children });
}
return patches;
}
// Reconciliation renders only the patches
// React does this internally via ReactDOM.render()
The virtual DOM does not make everything faster — it optimizes the common case of frequent, small updates. For very simple pages, direct DOM manipulation can be faster. The value of the virtual DOM is providing a declarative programming model with acceptable performance.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro