Skip to content

Lesson 17 of 37Effects and beyond

How Rendering Works

Follow an update from trigger to render to commit, and see how React diffs trees, preserves state, and stays responsive.

17 min read0/5 questions

Most confusing React behaviour (a component that re-renders "for no reason", state that survives when you expected it to reset, a list that loses its input text) makes sense once you know what React does between setState and the pixels changing. This is also the classic senior interview topic: "explain the virtual DOM and reconciliation".

Trigger, render, commit

Every screen update goes through three steps.

  1. Trigger. Something asks for an update: the first root.render(<App />), or a state setter like setCount.
  2. Render. React calls your components to find out what the UI should look like. The result is a tree of plain objects (React elements), sometimes called the virtual DOM. Nothing on screen changes in this step.
  3. Commit. React compares the new tree with the previous one and applies the minimum set of changes to the real DOM. Then the browser paints, and then effects run.

"Rendering" in React means calling your function, not touching the DOM. A component can render and produce exactly the same output, in which case the commit changes nothing.

What re-renders when state changes

When a component's state changes, React re-renders that component and everything below it, by default. It does not re-render parents or siblings.

A state change in TodoPage
AppHeaderAddTodoItem: Buy milkItem: Write testsTodoListTodoPagetodos state lives hereFooterroot

The first render calls every component once, top to bottom.

1/5

Watch it happen. Each component logs when it renders.

ReactWhoRenders.tsx
import { useState } from "react"; function Header() { console.log("render Header"); return <h3 style={{ margin: 0 }}>Todos</h3>;} function Item({ text }: { text: string }) { console.log("render Item", text); return <li>{text}</li>;} function TodoPage() { const [todos, setTodos] = useState(["Buy milk"]); console.log("render TodoPage"); return ( <div> <button onClick={() => setTodos([...todos, "Todo " + (todos.length + 1)])}>Add</button> <ul>{todos.map((t) => <Item key={t} text={t} />)}</ul> </div> );} export default function App() { console.log("render App"); return ( <div> <Header /> <TodoPage /> </div> );}
Quick check
In the tree above, TodoList holds a filter state and the user changes it. Which components re-render?
Need a nudge? A hint rules out a wrong answer.

Reconciliation: how React diffs two trees

Comparing two arbitrary trees perfectly is very slow (roughly O(n³)). React uses two assumptions to make it O(n):

  • Different element type, different tree. If a <div> becomes a <section>, or <Counter> becomes <Timer>, React throws away the old subtree (unmounting components and losing their state) and builds a new one.
  • Keys identify children. In a list, React matches old and new children by key. Same key, same component instance, state kept. New key, new instance.

If the type and key at a position stay the same, React keeps the instance and its state and only updates the props. State belongs to a position in the tree, not to the component function.

ReactStateByPosition.tsx
import { useState } from "react"; function Counter({ label }: { label: string }) { const [n, setN] = useState(0); return <button onClick={() => setN(n + 1)}>{label}: {n}</button>;} export default function App() { const [isFancy, setIsFancy] = useState(false); const [wrapInSection, setWrapInSection] = useState(false); const counter = <Counter label={isFancy ? "Fancy" : "Plain"} />; return ( <div style={{ display: "grid", gap: 8, maxWidth: 300 }}> <label><input type="checkbox" checked={isFancy} onChange={(e) => setIsFancy(e.target.checked)} /> Change the label prop</label> <label><input type="checkbox" checked={wrapInSection} onChange={(e) => setWrapInSection(e.target.checked)} /> Wrap in a section instead of a div</label> {wrapInSection ? <section>{counter}</section> : <div>{counter}</div>} </div> );}

Click the counter a few times. Changing the label keeps the count (same type, same position, new props). Switching the wrapper from div to section resets it to 0 (different type above it, whole subtree rebuilt).

Quick check
{isEditing ? <Form key="edit" /> : <Form key="new" />}. The user types into the form and then isEditing flips. What happens to the typed text?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/4 matched

What does React do with the old instance?

Choose an item, then its match on the other side.

Batching

Calling three setters in one event handler does not render three times. React batches all updates queued during an event and renders once afterwards. Since React 18 this also happens inside setTimeout, promises, and native event listeners (automatic batching).

Predict the outputJavaScript

The component has rendered once. What is the next line logged after one click?

function App() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
console.log("render", a, b);
function handleClick() {
  setA(1);
  setB(2);
  setA(a + 5);
}
return <button onClick={handleClick}>Go</button>;
}
Need a nudge? Hints walk you through it.

Fiber: rendering in small pieces

Before React 16, rendering was one recursive call that could not stop. A large update could freeze the page for hundreds of milliseconds while the user's typing waited. React rewrote its core as Fiber.

A fiber is a small object per component instance that records its type, props, state (the hook list from the custom hooks lesson lives here), and links to its parent, child, and sibling. Because the work is a linked structure instead of a call stack, React can process a few fibers, check whether something more urgent arrived (like a keystroke), pause, handle it, and resume or throw away the half-finished render.

Under the hood: two trees

React keeps two fiber trees: the current tree, matching what is on screen, and a work-in-progress tree it builds during render. Render work can be paused or discarded because it happens on the work-in-progress copy. When it is complete, the commit phase applies the DOM changes in one go (commit is never interrupted, so the user never sees a half-updated screen) and the work-in-progress tree becomes the new current tree.

Concurrent features: marking work as non-urgent

Interruptible rendering is what powers React's concurrent features. You tell React which updates are urgent (typing, clicking) and which can wait (filtering a big list).

  • useTransition gives you startTransition(fn). State updates inside fn are low priority and can be interrupted. isPending is true while the transition renders. In React 19, fn can also be async (an Action).
  • useDeferredValue(value) gives you a copy of value that lags behind during heavy renders, so the urgent part (the input) stays snappy.

Type quickly in the box below. Each item is artificially slow. With the deferred value, the input keeps up while the list catches up behind it.

ReactDeferredList.tsx
import { memo, useDeferredValue, useState } from "react"; function SlowItem({ text }: { text: string }) { const start = performance.now(); while (performance.now() - start < 1) {} // pretend this is expensive return <li>{text}</li>;} const SlowList = memo(function SlowList({ query }: { query: string }) { const items = Array.from({ length: 150 }, (_, i) => `${query || "item"} #${i + 1}`); return <ul style={{ maxHeight: 160, overflow: "auto" }}>{items.map((t) => <SlowItem key={t} text={t} />)}</ul>;}); export default function App() { const [query, setQuery] = useState(""); const deferredQuery = useDeferredValue(query); const isStale = query !== deferredQuery; return ( <div> <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Type quickly..." /> <div style={{ opacity: isStale ? 0.5 : 1 }}> <SlowList query={deferredQuery} /> </div> </div> );}
With useTransition instead
const [isPending, startTransition] = useTransition();
 
function handleTabClick(next: Tab) {
  startTransition(() => {
    setTab(next); // React may interrupt this render if the user clicks again
  });
}
Quick check
Which update is a good fit for startTransition?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

Reset state with a key

In this chat app the draft message leaks between contacts: type hi to Ada, switch to Sam, and the draft still says hi. React sees the same <Chat> at the same position, so it keeps its state.

Make the draft reset when you switch to a different contact, without moving the draft state up or adding effects. Clicking the contact you are already on must keep the draft.

  • The label reads Message to <name>.
  • Buttons: Ada, Sam, Priya.
React
import { useState } from "react"; function Chat({ contact }: { contact: string }) { const [draft, setDraft] = useState(""); return ( <div> <label htmlFor="draft">Message to {contact}</label> <input id="draft" type="text" value={draft} onChange={(e) => setDraft(e.target.value)} /> </div> );} export default function App() { const [contact, setContact] = useState("Ada"); return ( <div> {["Ada", "Sam", "Priya"].map((name) => ( <button key={name} onClick={() => setContact(name)}> {name} </button> ))} <Chat contact={contact} /> </div> );}
Key terms
render phase
React calls your components to compute the next UI tree. Pure and interruptible; nothing on screen changes.
commit phase
React applies the minimal DOM changes from the diff, then the browser paints and effects run.
reconciliation
Diffing the new element tree against the previous one, matching children by type and key.
Fiber
React's internal unit of work, one per component instance, which lets rendering pause, resume, and be discarded.
automatic batching
React groups several state updates into one render, including inside timeouts and promises.
transition
A low-priority update started with startTransition, which React can interrupt to keep the UI responsive.