How React Updates the Virtual DOM

This article explains the step-by-step mechanism React uses to update the Virtual DOM and keep your application’s user interface in sync with its state. You will learn about the trigger phase, the generation of a new Virtual DOM tree, the reconciliation process using the diffing algorithm, and how these changes are efficiently painted onto the real browser DOM.

1. The Trigger: State or Prop Changes

The process of updating the Virtual DOM always begins with a change in the application’s data. This happens when: * A component’s internal state is updated (e.g., via useState or setState). * New props are passed down from a parent component. * A context value changes.

When any of these events occur, React marks the affected component as “dirty” and schedules a re-render.

2. Creating a New Virtual DOM Tree

During a re-render, React calls the render function of the dirty component (and its children) to generate a brand new Virtual DOM tree. This tree is a lightweight, JavaScript object representation of the UI. React does not touch the real browser DOM at this stage; instead, it quickly constructs this new Virtual DOM tree in memory.

3. Reconciliation and the Diffing Algorithm

Once the new Virtual DOM tree is created, React compares it with the previous Virtual DOM tree—a snapshot taken just before the update. This comparison process is called Reconciliation.

To make this comparison highly performant, React uses a heuristic “diffing” algorithm based on two key assumptions: * Different Element Types: If two elements have different HTML tags or component types (e.g., swapping a <div> for a <span>), React assumes the entire subtree has changed. It tears down the old tree and builds the new one from scratch. * Keys for Lists: When rendering lists of elements, React uses the key prop to identify elements across renders. This allows React to detect if items have merely been reordered, inserted, or deleted, rather than re-rendering the entire list.

4. Batching and Updating the Real DOM

After calculating the exact differences (the “diff”) between the old and new Virtual DOMs, React computes the most efficient path to update the real browser DOM.

Instead of updating the real DOM immediately for every minor change, React batches these updates. It groups multiple changes together and applies them to the real DOM in a single write operation. This drastically reduces layout thrashing and repaints in the browser, which are historically the most expensive parts of web performance.