Sub topic 3
Your first useEffect: running code after render
What you should already know
This chapter assumes you can write function components with JSX, and that you use useState and understand that a state change triggers a re-render. You should also be comfortable with JavaScript closures and with reading the browser DOM. The previous chapters covered pure rendering and what counts as a side effect. This chapter shows the tool React gives you for running those side effects: useEffect.
The problem useEffect solves
A component's render body must be pure. Given the same props and state, it should return the same JSX and do nothing else. Updating document.title, starting a timer, or calling fetch changes something outside the component, so none of it belongs in the render body.
useEffect is a hook that lets you register a function to run after React has rendered and updated the screen. You describe the side effect. React decides when to run it.
Basic syntax
import { useEffect, useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}useEffect takes two arguments:
- A function, called the effect. React calls it after rendering.
- An optional array of dependencies. React compares it with the array from the previous render to decide whether to run the effect again.
Here the effect runs after the first render, and again after any render where count changed. If the component re-renders for another reason, such as a parent passing a new prop, count is unchanged and the effect is skipped.
When exactly does the effect run?
Each render is a snapshot of one pass through your component function. The sequence for one update looks like this:
Two points follow from this order:
- The effect never blocks the screen update in the normal case. Users see the new UI first, and the effect runs after.
- The effect sees the props and state from the render that scheduled it. In the example above, the effect from the render where
countis 3 readscountas 3, even if state changes again later.
In most cases React runs effects after the browser has painted. In rare cases, such as a click that triggers a discrete update, React may flush effects before paint. Do not depend on either ordering. If you need to measure the DOM before the user sees anything, that is a different hook, covered in a later chapter.
The three dependency shapes
The second argument controls when the effect runs. There are three forms.
| Form | Example | When the effect runs |
|---|---|---|
| No array | `useEffect(fn)` | After every render |
| Empty array | `useEffect(fn, [])` | After the first render only (plus the development double run described below) |
| Array with values | `useEffect(fn, [a, b])` | After the first render, then after any render where `a` or `b` changed |
React compares each dependency with the value from the previous render using Object.is. For primitives such as numbers and strings, this means "same value." For objects, arrays, and functions, it means "same reference." A new object created on every render is always "changed." A later chapter on unstable dependencies covers this in detail.
Omitting the array is rarely what you want. An effect that calls setState and has no array will trigger a render, which runs the effect, which calls setState again, and so on forever.
import { useEffect, useState } from 'react';
// Bug: no dependency array, and the effect sets state every time
function Broken() {
const [n, setN] = useState(0);
useEffect(() => {
setN(n + 1);
});
return <p>{n}</p>;
}Each render schedules an effect, the effect updates state, and the update causes another render. React will keep going until you close the tab or it gives up with a "Too many re-renders" style warning.
Rules for the dependency list
Treat the dependency array as a description of your code, not as a control you tune. The rule is simple: list every reactive value that the effect reads. Reactive values are props, state, and any variable or function declared inside the component body.
Values that are not reactive do not belong in the list. These include module-level constants, imports, and refs created with useRef (the ref object itself is stable, though its .current is not tracked).
import { useEffect, useState } from 'react';
const SITE_NAME = 'Notes'; // module-level, not reactive
function Page({ title }) {
const [unread, setUnread] = useState(0);
useEffect(() => {
document.title = `${SITE_NAME}: ${title} (${unread})`;
}, [title, unread]); // SITE_NAME is not listed
return <button onClick={() => setUnread(unread + 1)}>Unread: {unread}</button>;
}If you leave out a value the effect reads, the effect keeps using the old value from an earlier render. This bug is called a stale closure, and a later chapter covers it.
What the effect function may return
An effect may return a function. React calls it before running the effect again, and when the component unmounts. This is the cleanup function, and the next chapter covers it. For now, remember one constraint: the effect function itself must return either nothing or a function. This matters when you use async:
// Wrong: an async function returns a Promise, not a cleanup function
useEffect(async () => {
const res = await fetch('/api/data');
setData(await res.json());
}, []);
// Right: define the async function inside and call it
useEffect(() => {
async function load() {
const res = await fetch('/api/data');
setData(await res.json());
}
load();
}, []);React warns about the first form because it cannot treat a Promise as a cleanup function. The second form is valid. It still lacks race protection, which a later chapter on data fetching adds.
Effects run twice in development
In development, when your app is wrapped in <StrictMode>, React mounts each component, immediately unmounts it, and mounts it again. Your effect runs, cleans up, and runs again. This is deliberate. It exposes effects that cannot be undone. Production builds run the effect once.
You can see it with a log statement:
import { useEffect } from 'react';
function Hello() {
useEffect(() => {
console.log('effect ran');
}, []);
return <p>Hello</p>;
}In development with Strict Mode you will see "effect ran" twice on mount. This is not a bug in your component. Do not remove Strict Mode or add a guard flag to hide it. Fix the effect so a second run is harmless, usually by adding a cleanup function.
Common mistakes
- Putting event logic in an effect. If something should happen because the user clicked a button, do it in the click handler. Effects are for synchronizing with something outside React because the component is on screen.
- Copying props into state with an effect. If a value can be calculated from props or state during render, calculate it there. An effect adds an extra render and a window where the two values disagree.
- Using
[]to mean "I don't want to think about dependencies." An empty array says the effect reads no reactive values. If it does read some, you have a stale closure. - Mutating state inside render instead of an effect. Render must stay pure. Move the side effect into
useEffect.
A worked example
This component keeps the browser tab title in sync with a draft's name, and shows what happens when each render is compared with the last one.
import { useEffect, useState } from 'react';
export default function Draft() {
const [name, setName] = useState('Untitled');
const [saves, setSaves] = useState(0);
useEffect(() => {
console.log('title effect, name =', name);
document.title = `Editing ${name}`;
}, [name]);
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={() => setSaves(saves + 1)}>Save ({saves})</button>
</div>
);
}Trace the behavior:
- First render: the effect runs and sets the title to "Editing Untitled".
- You type "A" in the input.
namechanges, so the effect runs again. - You click Save.
saveschanges and the component re-renders, butnameis the same, so the effect is skipped. The console stays quiet.
The effect depends only on name, so changes to saves do not touch the title. That is the behavior the dependency array is meant to describe.
Exercise
A component has const [count, setCount] = useState(0) and an effect useEffect(() => { document.title = count; }, []). A user clicks a button that increments count three times. What does the tab title show afterward, and what is the fix?
Show answer
The title still shows 0. The empty array tells React the effect reads no reactive values, so it runs only after the first render. The effect reads count, so the fix is to change the dependency array to [count].
Exercise
Why is useEffect(async () => { ... }, []) a mistake, and how do you write it correctly?
Show answer
An async function always returns a Promise, but React expects an effect to return nothing or a cleanup function. Declare an async function inside the effect, call it, and let the effect itself stay synchronous.