Sub topic 4
The Render Phase and the Commit Phase
This chapter assumes you can write function components, use useState, read JSX, and know that the browser DOM is a tree of nodes you can read and change from JavaScript. It builds the working model of what happens between a state change and an updated screen, and then covers the errors people commonly make because of it.
Three words that get mixed up
People use "render" for several different things. React's documentation separates the work into three steps:
- Trigger. Something asks React to produce a new screen: the first mount, or a state update.
- Render. React calls your components to find out what the UI should look like.
- Commit. React applies the needed changes to the DOM.
"Rendering" in React does not mean drawing pixels or touching the DOM. It means calling your component functions. The browser paints after the commit, and that is a fourth step React does not control.
The trigger
A render starts in one of two ways:
- The initial render, when you call
createRoot(...).render(<App />). - A state update in a component, such as a call to a
setStatefunction returned byuseState.
When you call a setter, React does not change the variable in your running function. It records the new value and schedules a new render of that component. This example shows the cycle:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
console.log('Counter rendered with count', count);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}On mount, the log prints count 0. Each click calls setCount, React calls Counter again, and the log prints the new number. The log line appears during the render phase, before the DOM changes. If you open the browser's element inspector while clicking, you will see the button text change only after the log.
The render phase
In the render phase, React starts at the component that needs updating and calls it. The function returns elements, which are plain objects describing the UI. React then looks at the elements returned, finds child components, and calls those too. This continues down the tree.
Three facts matter most:
- Rendering is recursive. When a component re-renders, React by default re-renders all of its children, even if their props did not change. A later chapter covers how to skip this with memoization.
- Rendering is a calculation. A component should take props and state and return elements. It should not change anything outside itself while it runs.
- Rendering does not guarantee a DOM change. React may call your component and then find that the output matches the previous output. In that case it changes nothing in the DOM.
The result of the render phase is a new tree of elements, which React compares with the previous tree. That comparison is called reconciliation, and the next chapters cover it in detail. For this chapter, treat it as the step that produces a list of changes.
The commit phase
In the commit phase, React applies the list of changes to the DOM.
- On the initial render, React creates DOM nodes with
appendChildand similar calls. - On a re-render, React changes only the DOM nodes that differ: a text value, an attribute, an added or removed node.
The commit phase is synchronous. Once React starts it, it finishes it without yielding to other work, so the DOM never shows a half-applied update. After React updates the DOM, it updates refs and runs layout effects. The browser then paints the new screen.
You can see the "only what differs" rule in the browser. Put an <input> and a counter in the same component, type some text into the input, and click the counter button. The text in the input stays, because React changed only the text node holding the count.
Render is not commit
Because the two phases are separate, a component can render without any DOM work happening. The following table summarizes the differences.
| Row | Render phase | Commit phase |
|---|---|---|
| What happens | Components are called, elements are returned | DOM is changed, refs are attached |
| Touches the DOM | No | Yes |
| Can be repeated or discarded | Yes | No |
| Allowed side effects | None | Layout effects run here, then effects after paint |
| Can be interrupted | Yes, in concurrent rendering | No |
The row about repetition is the important one. React is allowed to call your component more than once for a single update, throw the result away, or pause halfway. This is why render functions must be pure, which the Strict Mode chapter covers. A render that sends a network request or changes a variable outside the component is wrong, because you cannot predict how many times it will run.
Batching: one render per event
React groups state updates so that one event leads to one render. Updates in an event handler are queued, and React processes the whole queue after the handler finishes. The second example shows the consequence:
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
function addTwoWrong() {
setCount(count + 1);
setCount(count + 1); // both use the same count from this render
}
function addTwoRight() {
setCount(c => c + 1);
setCount(c => c + 1); // updater functions queue up and apply in order
}
return (
<>
<p>{count}</p>
<button onClick={addTwoWrong}>+2 (actually +1)</button>
<button onClick={addTwoRight}>+2</button>
</>
);
}Inside one render, count is a constant. Both calls in addTwoWrong read the same value, say 0, and both queue "set to 1". The result is 1. In addTwoRight, each updater receives the result of the previous one, so 0 becomes 1 and then 2. Both buttons cause only one re-render.
Batching also means that the value you read right after calling a setter is still the old one:
function handleClick() {
setCount(count + 1);
console.log(count); // still the value from this render
}This is the same fact as before. The variable belongs to the render that created the handler, and the new value appears in the next render.
Effects relative to the phases
Effects are the escape hatch for work that must happen because of rendering, such as starting a subscription or reading layout. They never run during the render phase. They run after the commit:
| Hook | When it runs |
|---|---|
| `useLayoutEffect` | After the DOM is updated, before the browser paints |
| `useEffect` | After the commit, usually after the browser paints |
The order for one update is: render, commit, layout effects, paint, effects. This explains a common observation. If you read an element's size inside the render function, you get the old layout, because the DOM has not changed yet. If you read it in a layout effect, you get the new layout. Use useLayoutEffect only when you must measure or change the DOM before the user sees the frame, because it delays painting.
import { useEffect, useLayoutEffect, useState } from 'react';
function Order() {
const [n, setN] = useState(0);
console.log('1. render', n);
useLayoutEffect(() => {
console.log('2. layout effect', n);
});
useEffect(() => {
console.log('3. effect', n);
});
return <button onClick={() => setN(n + 1)}>Click {n}</button>;
}Each click prints the three lines in numeric order. The numbers follow the phase order described above.
Common errors
Believing a re-render means the DOM was rebuilt. A component function runs, but React then compares the output and changes only the differences. Re-rendering is usually cheap. Do not optimize it until you have measured a problem.
Putting side effects in the render body. Code like document.title = x or fetch(...) directly in the component body runs on every render, and React may run it extra times. Move it into an effect or an event handler.
Mutating state objects. If you change an object or array in place and call the setter with the same reference, React sees the same value and may skip the update. Create a new object or array instead.
Reading state right after setting it. As shown above, the value is unchanged until the next render. Compute the next value in a local variable if you need it immediately.
Expecting a log in the effect to match a log in render. Each render has its own props, state, and handlers. An effect from render 3 sees the values of render 3, even if render 4 has already happened.
A worked trace
Take the Counter component and trace one click from start to finish.
- The user clicks. React runs the
onClickhandler. - The handler calls
setCount(1). React queues the update and marksCounteras needing a render.countin the handler is still0. - The handler finishes. React starts the render phase and calls
Counter.useStatereturns1. The log printsCounter rendered with count 1. Counterreturns a<button>element whose text isClicked 1 times.- React compares that element with the previous one and finds one difference: the text content.
- In the commit phase, React sets the text of the existing button node. It does not create a new button.
- The browser paints the updated button.
Steps 3 to 5 are the render phase, and step 6 is the commit phase. Nothing in step 3 or 4 touched the DOM.
Exercise
A component calls setCount(count + 1) three times in one click handler, starting from count = 5. How many renders happen, and what does count equal after the render? What change would make the result 8?
Show answer
One render happens, because React batches the three updates from a single event. The result is 6, because all three calls read the same count of 5 from the current render and queue "set to 6". Replacing each call with setCount(c => c + 1) makes each updater use the previous result, so the final value is 8.
Exercise
You need the pixel height of a <div> after a state change, so you can position a tooltip before the user sees the new frame. In which place should you read it: the component body, useEffect, or useLayoutEffect? Explain using the phases.
Show answer
Use useLayoutEffect. The component body runs in the render phase, before the DOM changes, so it would give the old height. useEffect runs after the browser may have painted, so the user could see the tooltip in the wrong position for one frame. useLayoutEffect runs after the commit has updated the DOM and before the paint, so it sees the new layout and can adjust before the user sees anything.