Learn the concept
React Internals
The Virtual DOM is a lightweight JavaScript object representation of the real DOM. When state changes, React creates a new virtual DOM tree, diffs it against the previous one, and applies only the minimal necessary changes to the actual DOM.
What is the Virtual DOM?
The Virtual DOM (VDOM) is a programming concept where a virtual representation of the UI is kept in memory as plain JavaScript objects. Each React element — created by JSX or createElement() — is a simple object describing a DOM node:
{ type: 'div', props: { className: 'card', children: [...] } }These objects form a tree that mirrors the real DOM structure but is much cheaper to create and manipulate than actual DOM nodes.
Why Does React Use It?
Direct DOM manipulation is expensive. Every time you change a DOM node, the browser may need to recalculate styles, recompute layout, repaint pixels, and recomposite layers. The Virtual DOM lets React batch and minimize these operations.
How the Update Cycle Works:
The Two Heuristics:
React's diffing algorithm achieves O(n) complexity using two assumptions:
Different types produce different trees — If an element changes from <div> to <span>, React tears down the entire old subtree and builds a new one. It does not attempt to match children across different types.
Keys identify stable elements — When diffing children of the same parent, React uses key props to match elements across renders. This is why keys are critical for lists — without them, React falls back to index-based matching which breaks with reordering.
Important Nuances:
// JSX
const element = <h1 className="title">Hello</h1>;
// Compiles to a plain JavaScript object:
const element = {
type: 'h1',
props: {
className: 'title',
children: 'Hello'
}
};
// Nested elements create a tree of these objects:
const card = (
<div className="card">
<h2>Title</h2>
<p>Description</p>
</div>
);
// Becomes:
const card = {
type: 'div',
props: {
className: 'card',
children: [
{ type: 'h2', props: { children: 'Title' } },
{ type: 'p', props: { children: 'Description' } }
]
}
};Dashboards with frequently changing data rely on the VDOM to efficiently update only the cells or charts that changed, not the entire page.
When new messages arrive, the VDOM ensures only the new message elements are added to the DOM while existing messages remain untouched.
Build a component that renders the VDOM tree as a visual diagram, highlighting which nodes change on each state update.
Create the same dynamic list with both raw DOM manipulation and React, measuring DOM operation counts to see the VDOM's efficiency.