Loading lessons...
The Virtual DOM & Reconciliation
The Virtual DOM & Reconciliation
Directly manipulating the Real DOM in modern web applications is computationally expensive. React solves performance bottlenecks by introducing the Virtual DOM (VDOM).
What is the Virtual DOM?
The Virtual DOM is a lightweight, in-memory tree representation of the actual DOM nodes. Whenever state changes occur in a React application:
- React creates a new Virtual DOM tree representing the updated state.
- React compares the new Virtual DOM tree with the previous Virtual DOM tree using a fast diffing algorithm. This process is called Reconciliation.
- React calculates the minimum set of changes required and updates only those specific nodes in the Real DOM (a process called Commit).
[ State Change ] -> [ New Virtual DOM ] -> [ Diffing Algorithm ] -> [ Batch Real DOM Update ]
The Diffing Algorithm (Reconciliation Rules)
React relies on two main heuristics to achieve $O(n)$ diffing time complexity:
- Different Element Types: If two elements have different types (e.g.,
<div>changes to<span>), React tears down the old tree and builds the new tree from scratch. - Keys for Lists: When rendering lists of elements, React uses the
keyprop to keep track of items across renders, avoiding unnecessary re-renders when list order changes.
| Aspect | Real DOM | Virtual DOM |
|---|---|---|
| Speed | Slow direct layout & repaint operations | Fast in-memory JS object operations |
| Memory | High browser DOM object overhead | Lightweight JS plain objects |
| Updates | Immediate element tree redraw | Batched, minimal actual DOM patches |
// Example showing why keys are important during reconciliation
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Summary & TL;DR
- The Virtual DOM is a lightweight memory copy of the real DOM.
- Reconciliation is React's process of diffing the old VDOM against the new VDOM.
- React batches updates and applies only the calculated differences to the Real DOM.
- Using unique
keyprops in lists allows React to optimize list updates efficiently.