The Virtual DOM (VDOM) is a tree-like data structure that mimics the structure of the Real DOM using plain JavaScript objects.
🔹 Structure of Virtual DOM:
- Each element in the Virtual DOM is represented as a JavaScript object (node).
- These nodes contain:
type: The HTML tag name or React component type.props: Attributes/props of the element (e.g. className, id).children: An array of child Virtual DOM nodes.
🔸 Example
React JSX:
const element = <div className="container"><h1>Hello</h1></div>;
Equivalent Virtual DOM object:
{
type: "div",
props: {
className: "container",
children: [
{
type: "h1",
props: {
children: "Hello"
}
}
]
}
}
🔹 Key Characteristics:
- It’s a JavaScript representation of the UI.
- Immutable – When changes happen, a new Virtual DOM is created.
- It uses diffing to compare the old and new tree.
- Only changed nodes are updated in the Real DOM (via reconciliation).
🔸 How React uses it:
- Create VDOM from JSX.
- Render initial UI from the VDOM.
- On state/prop changes:
- New VDOM is created.
- React compares (diffs) new vs old VDOM.
- Only the actual changes are applied to the browser DOM.
✅ Conclusion:
The Virtual DOM is an efficient abstraction layer used by React to minimize direct DOM manipulation, improving performance and UI responsiveness.