Sub topic 9
When Effects Run Relative to Rendering and Commit
This chapter assumes you know useState, basic JSX, and that a component function returns a description of UI. It also assumes you have read the chapter on the render phase and the commit phase. Here the focus is on where effects fit into that sequence, and the mistakes that come from misplacing them.
Effects live outside the render phase
Rendering must be a pure calculation. An effect is code that does something to the world outside that calculation: it starts a subscription, sets a timer, sends a request, or touches the DOM by hand. React therefore does not run effects while it renders. It runs them after it has committed the result to the DOM.
The order for one update is:
- A state change schedules a render.
- React calls your component functions (render phase). Effects do not run here.
- React updates the DOM (commit phase).
- The browser can paint.
- React runs cleanup functions from the previous effects, then runs the new effects.
A consequence is that code in the component body runs before the DOM reflects the new state, while code in an effect runs after. The next example logs both so you can see the order.
import { useEffect, useState } from 'react';
function Title() {
const [count, setCount] = useState(0);
console.log('1. render, count =', count);
useEffect(() => {
console.log('2. effect, DOM text is', document.title);
document.title = `Clicked ${count} times`;
return () => console.log('3. cleanup for count =', count);
}, [count]);
return <button onClick={() => setCount(count + 1)}>Click</button>;
}After the first click, the console shows the render log for count = 1 first. Then it shows the cleanup for count = 0, and then the effect for count = 1. The cleanup belongs to the previous render, so it sees the old count.
The dependency array decides whether an effect runs
After each commit, React compares the dependency array with the one from the previous render. It uses Object.is on each item.
| Dependency array | When the effect runs |
|---|---|
| Omitted | After every commit |
| `[]` | After the first commit only (and its cleanup on unmount) |
| `[a, b]` | After the first commit, and after any commit where `a` or `b` changed |
Each render has its own effect closure. The effect sees the props and state from the render that created it. This is why you must list every reactive value the effect reads. If you leave one out, the effect keeps using a stale value from an earlier render.
import { useEffect, useState } from 'react';
function Ticker() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
// Stale: this closure always sees count = 0 because deps is []
console.log('count is', count);
}, 1000);
return () => clearInterval(id);
}, []); // missing dependency: count
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}The fix depends on intent. If the interval should read the latest value, add count to the array, and the interval restarts on each change. If you only need to update state, use the updater form, setCount(c => c + 1), and the dependency is no longer needed.
Objects and functions created in the component body are new on every render. If one is in the dependency array, the effect runs after every commit. Move the value inside the effect, move it outside the component, or derive a primitive from it.
Cleanup: the other half of an effect
React runs a cleanup function in two situations: before re-running the effect because its dependencies changed, and when the component is removed from the tree. Cleanup is where you undo what the setup did.
import { useEffect, useState } from 'react';
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
const socket = new WebSocket(`wss://example.com/rooms/${roomId}`);
socket.onmessage = event => {
setMessages(prev => [...prev, event.data]);
};
return () => socket.close();
}, [roomId]);
return <p>{messages.length} messages in {roomId}</p>;
}When roomId changes, React closes the old socket and opens a new one. The sequence is cleanup of the old effect, then setup of the new one. Both happen after the commit that shows the new room.
Cleanup also protects against out-of-order results. If a fetch for room A finishes after the user has moved to room B, you do not want to store the old data:
import { useEffect, useState } from 'react';
function UserName({ userId }) {
const [name, setName] = useState(null);
useEffect(() => {
let ignore = false;
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(user => {
if (!ignore) setName(user.name);
});
return () => {
ignore = true;
};
}, [userId]);
return <p>{name ?? 'Loading...'}</p>;
}Connection to reconciliation: state and effects follow identity
Effects belong to a component instance. React decides whether an instance survives an update using type and position, and keys, as covered in the earlier chapters. This has direct effects on cleanup:
- If the instance is preserved, its effects re-run only when dependencies change.
- If the instance is removed, its cleanups run. A new instance in its place runs its setup from scratch.
- Changing a
keyremoves the old instance and creates a new one, so every effect cleans up and starts again, even with an empty dependency array.
useEffect and useLayoutEffect
useEffect normally runs after the browser has had a chance to paint. That keeps effects from delaying the first visual update. The downside is that if an effect changes something visible, the user can briefly see the state before the change.
useLayoutEffect runs after React has updated the DOM but before the browser paints. Use it when you must measure the DOM and adjust before the user sees anything, such as positioning a tooltip based on its measured size.
import { useLayoutEffect, useRef, useState } from 'react';
function Tooltip({ text }) {
const ref = useRef(null);
const [height, setHeight] = useState(0);
useLayoutEffect(() => {
setHeight(ref.current.getBoundingClientRect().height);
}, [text]);
return (
<div ref={ref} style={{ marginTop: -height }}>
{text}
</div>
);
}Here the measurement triggers a state update. Because it happens in a layout effect, React re-renders and commits again before the browser paints, so the user never sees the unadjusted position.
| Row | `useEffect` | `useLayoutEffect` |
|---|---|---|
| Runs | After commit, usually after paint | After commit, before paint |
| Blocks painting | No | Yes |
| Typical use | Subscriptions, fetches, logging | Measuring and adjusting layout |
An update caused by a discrete user event, such as a click, can cause React to run the pending effects of that render before the browser paints. Do not depend on "after paint" as a guarantee. Depend only on "after commit".
Effects run again in Strict Mode development builds
In development, Strict Mode mounts each component, runs its effects, runs the cleanups, and runs the effects again. This simulates a component being removed and restored. It does not happen in production.
If your effect is correct, you will not notice the extra cycle, because cleanup undoes setup. If you see a duplicate connection, a doubled log, or a subscription that never ends, the cleanup is missing or incomplete. Treat the repeated run as a bug report, not something to suppress.
Common mistakes
- Using an effect to compute values from props or state. If you can calculate it during render, do that. An effect that calls
setStatewith a derived value causes an extra render after the first commit. - Using an effect to respond to a user action. Put that logic in the event handler. The handler knows exactly what the user did, while an effect only knows that something changed.
- Omitting dependencies to silence a warning. This causes stale values. Change the code so the dependency is not needed, rather than hiding it.
- Forgetting cleanup. Timers, listeners, and sockets accumulate on every re-run.
- Setting state unconditionally in an effect with that state as a dependency. This creates an infinite loop: commit, effect, state change, render, commit.
- Assuming effects run in the render phase. They do not, so you cannot use an effect to change what the current render outputs.
Exercise
A component has useEffect(() => { document.title = name; }, []) where name is a prop. The title never updates when name changes. Why, and what is the fix? Also, when would the effect run again if you gave the parent a key={name} for this component instead?
Show answer
The empty array means React runs the effect only after the first commit, and the closure keeps the name from that first render. Fix it by changing the array to [name], so the effect re-runs after any commit where name changed. If the parent used key={name} on the component, a new name would give a new key, so React would remove the old instance (running its cleanup) and mount a new one, which would run the effect again even with []. That works, but it also resets all of the component's state, so the dependency array is the better fix here.
Exercise
In the ChatRoom example, the user switches from room "a" to room "b". List the order of these four events: render with roomId = "b", DOM commit, close socket for "a", open socket for "b".
Show answer
Render with roomId = "b", then DOM commit, then close the socket for "a" (cleanup of the old effect), then open the socket for "b" (setup of the new effect). Rendering and committing come first. The cleanup and setup run afterward as part of effect processing.