Lesson 2 +10 XP

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:

  1. React creates a new Virtual DOM tree representing the updated state.
  2. React compares the new Virtual DOM tree with the previous Virtual DOM tree using a fast diffing algorithm. This process is called Reconciliation.
  3. 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:

  1. 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.
  2. Keys for Lists: When rendering lists of elements, React uses the key prop to keep track of items across renders, avoiding unnecessary re-renders when list order changes.
AspectReal DOMVirtual DOM
SpeedSlow direct layout & repaint operationsFast in-memory JS object operations
MemoryHigh browser DOM object overheadLightweight JS plain objects
UpdatesImmediate element tree redrawBatched, 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 key props in lists allows React to optimize list updates efficiently.