← Back to React, page 2

react-0026 · Easy fresher

What is the virtual DOM, and how does React's reconciliation decide what to update?

When state changes, React calls your components again to produce a new tree of plain objects describing the UI, often called the virtual DOM. It compares the new tree with the previous one and works out the smallest set of changes. Then it applies only those changes to the real DOM. Elements of the same type at the same position are updated in place, and a different type is replaced, which resets state below it.

Full answer

Updating the real DOM directly is slow when done carelessly, and hand-written update code is error-prone. React lets you describe the whole UI for the current state. It then handles the changes.

Every render produces React elements, which are lightweight objects. The collection of these elements is the "virtual DOM". It is a description, not a copy of the browser's DOM. React keeps the previous tree, builds the next tree, and compares them. This comparison step is called reconciliation, and the engine behind it is called Fiber.

A full tree comparison would be expensive, so React uses two assumptions. First, if two elements have different types (a div becomes a section, or one component becomes another), React tears down the old subtree and builds the new one. All state in the old subtree is lost. Second, in a list, keys identify items, so React can match elements that moved. Without keys, matching is by position.

For elements of the same type, React keeps the same DOM node and updates only the changed attributes and children. That is why typing in an input does not recreate the input.

React finishes with a commit phase, which applies the collected changes to the DOM in one go, and then runs layout effects and effects. The render phase can be paused or restarted in concurrent mode, while the commit phase cannot.

Saying "the virtual DOM is faster than the DOM" is a weak claim. It is a tool that makes declarative code affordable. The code below shows the DOM node being reused for a text change and replaced for a tag change.

jsx
import { useEffect, useRef, useState } from 'react';

export default function Demo() {
  const [title, setTitle] = useState('Marks');
  const [asSection, setAsSection] = useState(false);
  const nodeRef = useRef(null);
  const previous = useRef(null);

  useEffect(() => {
    if (previous.current !== null) {
      console.log('same DOM node reused: ' + (previous.current === nodeRef.current));
    }
    previous.current = nodeRef.current;
  });

  return (
    <div>
      <button onClick={() => setTitle('Results')}>Change text</button>
      <button onClick={() => setAsSection(true)}>Switch tag</button>
      {asSection ? (
        <section ref={nodeRef}>{title}</section>
      ) : (
        <div ref={nodeRef}>{title}</div>
      )}
    </div>
  );
}

The first click changes only the text, so React updates the existing node. The second click changes the element type from div to section, so React replaces the node. Output of the run: same DOM node reused: true same DOM node reused: false

Key points

  • The virtual DOM is a tree of lightweight elements describing the UI. It is not the real DOM.
  • Reconciliation compares the new tree with the previous one and produces a minimal set of changes.
  • Same type at the same position means update in place. A different type means replace and reset state.
  • Keys let React match list items that move.
  • The commit phase applies changes to the DOM in one step.

Common mistakes

  • Saying the virtual DOM is a copy of the real DOM.
  • Claiming the virtual DOM is always faster than direct DOM updates.
  • Defining components inside other components, which gives a new type on every render and remounts them.
  • Forgetting that a different element type resets state below it.

Follow-ups

  • Why does a component defined inside another component lose its state on each render?
  • How do keys change the comparison for lists?
  • What is the difference between the render phase and the commit phase?

Tips

  • Avoid the "virtual DOM is fast" slogan. Say what it enables: describe UI declaratively, update minimally.
  • State the two heuristics (type and key). They show you know how it works.
  • Use "render phase" and "commit phase" to show structure.