Sub topic 3
How a State Update Triggers a Re-render
This chapter assumes you can write function components, pass props, and use arrow functions and destructuring. You should also have seen useState declared once. Here you will learn what happens between calling a setter and seeing new output on screen.
The three phases: trigger, render, commit
React updates the screen in three phases.
- Trigger. Something requests an update. For state, this is a call to a setter such as
setCount. The first mount of the app is also a trigger. - Render. React calls your component function to find out what the UI should look like. "Render" here means "run your function". It does not mean "draw pixels".
- Commit. React compares the new output with the previous output and changes only the parts of the browser DOM that differ.
The browser then paints. A render can happen without any DOM change. If your component returns the same output as before, the commit step has nothing to apply.
What a setter call does
A setter does not change the variable in your current function call. It adds a request to a queue and tells React that this component needs a new render.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
console.log('render, count =', count);
function handleClick() {
setCount(count + 1);
console.log('after setCount, count =', count);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}The first click logs after setCount, count = 0, and then render, count = 1. The order matters:
- The handler finishes first, with the old value still in
count. - React then re-renders
Counter. In that new call,useStatereturns the new value,1.
Each render is a separate function call with its own count. The next chapter develops this idea as the snapshot model.
How React remembers state between calls
The count variable lives inside a function call that ends. React stores the real state value outside your function, attached to that component instance in the tree. When useState(0) runs, React looks up the stored value for this position and returns it. The argument 0 is used only on the first render.
React matches useState calls by the order in which they run. This is why Hooks must be called at the top level, never inside conditions or loops. If the order changed between renders, React would hand the wrong value to the wrong variable.
import { useState } from 'react';
function Broken({ showName }) {
// Wrong: the number of useState calls changes between renders.
if (showName) {
const [name, setName] = useState('');
}
const [age, setAge] = useState(0);
return <p>{age}</p>;
}React reports this as an error about a change in the order of Hooks. Move the call out of the condition and use the condition in the returned JSX instead.
What gets re-rendered
When a component's state changes, React re-renders that component and then all of its children, recursively. It does this even if a child's props did not change.
import { useState } from 'react';
function Child() {
console.log('Child rendered');
return <p>I am a child</p>;
}
function Parent() {
const [n, setN] = useState(0);
console.log('Parent rendered');
return (
<>
<button onClick={() => setN(n + 1)}>Count: {n}</button>
<Child />
</>
);
}Each click logs both Parent rendered and Child rendered. Siblings and ancestors of the component that owns the state are not re-rendered, unless a parent above them also re-renders.
This default is usually fine, because rendering is just calling functions and comparing results. Keep it in mind for two practical reasons:
- Put state as low in the tree as it can go. State in
Parentre-renders everything underParent. - Render functions must be cheap and free of side effects. React may call them more than once.
The tool for skipping child renders is React.memo. It is an optimization, so measure before adding it.
When React skips the update
If you set state to the same value, React can bail out. It compares the new value with the current one using Object.is.
import { useState } from 'react';
function Toggle() {
const [on, setOn] = useState(false);
console.log('render');
return (
<>
<button onClick={() => setOn(false)}>Set off</button>
<p>{on ? 'On' : 'Off'}</p>
</>
);
}Clicking "Set off" while on is already false does not change the screen. React may still call Toggle once more before it stops, but it will not re-render the children or commit anything. Do not rely on the function running or not running.
This check is by identity for objects and arrays, which leads to a common error:
import { useState } from 'react';
function Profile() {
const [person, setPerson] = useState({ name: 'Ada' });
function wrongRename() {
person.name = 'Grace'; // mutates the same object
setPerson(person); // same reference, so React sees no change
}
function rename() {
setPerson({ ...person, name: 'Grace' }); // new object
}
return (
<>
<p>{person.name}</p>
<button onClick={wrongRename}>Broken rename</button>
<button onClick={rename}>Rename</button>
</>
);
}wrongRename passes the same object back, so React treats it as "no change" and does not update the screen. A later render may show the mutated value, which makes the bug look random. Chapter 8 covers this in detail.
Setting state during render
Calling a setter in the body of the component, outside any handler, is an error in most cases. It triggers a render, which calls the setter again, and so on.
import { useState } from 'react';
function Loop() {
const [n, setN] = useState(0);
setN(n + 1); // schedules another render every time
return <p>{n}</p>;
}React stops this with a "Too many re-renders" error. The usual cause is writing onClick={setN(n + 1)} instead of onClick={() => setN(n + 1)}. The first form calls the setter immediately during render. The second passes a function that React calls on click.
Rendering and the screen are different
Several things can look like "the state did not update" but are really about timing:
| Symptom | Cause |
|---|---|
| `console.log(count)` right after `setCount` shows the old value | The handler runs with the snapshot from the render it belongs to. |
| A component logs twice in development | `StrictMode` calls render functions twice to expose impure code. |
| The component renders but nothing changes in the DOM | The output was identical, so the commit had nothing to apply. |
| The screen does not update after `setPerson(person)` | The reference is the same, so React skips the update. |
A mental checklist
When a screen looks wrong after a state change, ask these questions in order:
- Did the setter run at all? Add a log inside the handler.
- Did you pass a new value, or the same object or array reference?
- Is the component that owns the state the one you expect to update?
- Is the display derived from the state, or copied into a second variable that never changes?
Exercise
In the Counter example, a handler calls setCount(count + 1) and then immediately logs count. Why does the log show the old value, and when does the new value become available?
Show answer
The handler runs inside the function call for the current render, and count in that call is fixed. The setter only queues an update and schedules a render. React then calls the component again, and in that new call useState returns the updated value, so the new count is visible during the next render.
Exercise
A component calls person.age = 30; setPerson(person); and the screen does not update. Explain why, and write the correct call.
Show answer
The object is mutated in place, so the reference passed to the setter equals the current state according to Object.is. React treats it as no change. The correct call creates a new object: setPerson({ ...person, age: 30 });.
Exercise
A parent holds a counter in state and renders an unrelated <Footer /> child that logs on every render. Does Footer log when the counter changes? Name one way to avoid it without changing what the parent renders.
Show answer
Yes. React re-renders all children of a component whose state changed, even when their props are unchanged. You can wrap Footer in React.memo so it skips rendering when its props are equal, or move the counter state into its own component so Footer is no longer one of its children.