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
- Trigger: a state update (
setState, a reducer dispatch, a context change, or the initialroot.render). - Schedule: updates are queued and batched automatically (React 18+). Urgent updates (typing) get higher priority than transitions.
- 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.
- Reconciliation: compares element types and keys to decide what to keep, update, move or remove.
- Commit phase (synchronous):
- Apply DOM insertions, updates and deletions.
- Attach refs (and run ref cleanup functions from React 19).
- Run
useLayoutEffectcallbacks (before the browser paints).
- Browser paints.
- Passive effects:
useEffectcallbacks run after paint.
Reconciliation rules
- Different element type (
<div>to<span>,ComponentAtoComponentB): 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:
keyprops 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";23export function Phases() {4 const [open, setOpen] = useState(false);5 const boxRef = useRef<HTMLDivElement>(null);67 console.log("1. render phase: compute JSX, no side effects here");89 useLayoutEffect(() => {10 // 2. after DOM mutation, before paint: safe to measure11 console.log("2. layout effect, height =", boxRef.current?.offsetHeight);12 }, [open]);1314 useEffect(() => {15 // 3. after paint: subscriptions, fetching, logging16 console.log("3. passive effect");17 }, [open]);1819 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.