ReactMedium

How does React update the DOM?

React updates the DOM in two phases. In the render phase it calls your components to compute the new UI and diffs it against the previous tree. In the commit phase it applies the needed DOM mutations in one go, then runs layout effects and, after paint, regular effects.

Step by step

  1. Trigger: a state update (setState, a reducer dispatch, a context change, or the initial root.render).
  2. Schedule: updates are queued and batched automatically (React 18+). Urgent updates (typing) get higher priority than transitions.
  3. Render phase: React calls the components that need updating and builds a new fiber tree. This phase is pure and can be interrupted, paused or restarted in concurrent mode.
  4. Reconciliation: compares element types and keys to decide what to keep, update, move or remove.
  5. Commit phase (synchronous):
    • Apply DOM insertions, updates and deletions.
    • Attach refs (and run ref cleanup functions from React 19).
    • Run useLayoutEffect callbacks (before the browser paints).
  6. Browser paints.
  7. Passive effects: useEffect callbacks run after paint.

Reconciliation rules

  • Different element type (<div> to <span>, ComponentA to ComponentB): tear down the old subtree and build a new one; state is lost.
  • Same type: keep the DOM node and update changed attributes; component state is preserved.
  • Lists: key props match items between renders.

Why it matters

Knowing the phases explains why you should not cause side effects during render, why useLayoutEffect exists for measurements, and why state "does not update immediately".

Code example

tsx
1import { useEffect, useLayoutEffect, useRef, useState } from "react";
2
3export function Phases() {
4 const [open, setOpen] = useState(false);
5 const boxRef = useRef<HTMLDivElement>(null);
6
7 console.log("1. render phase: compute JSX, no side effects here");
8
9 useLayoutEffect(() => {
10 // 2. after DOM mutation, before paint: safe to measure
11 console.log("2. layout effect, height =", boxRef.current?.offsetHeight);
12 }, [open]);
13
14 useEffect(() => {
15 // 3. after paint: subscriptions, fetching, logging
16 console.log("3. passive effect");
17 }, [open]);
18
19 return (
20 <div>
21 <button onClick={() => setOpen((o) => !o)}>Toggle</button>
22 <div ref={boxRef}>{open && <p>Now you see me</p>}</div>
23 </div>
24 );
25}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app