React / 29
useEffect, step by step
Run code after React updates the screen, like fetching data or starting a timer, control how often it re-runs, and clean it up when you're done.
The shape
import { useEffect } from "react";
useEffect(() => {
// setup: runs after the render is on screen
return () => {
// cleanup (optional): undo the setup
};
}, [dependencies]);Two arguments:
- A setup function: the side effect. It can return a cleanup function.
- A dependency array (optional): the values the effect uses. It decides how often the effect re-runs.
When does it run?
1 · render
React calls your component
2 · commit
React updates the DOM
3 · paint
The browser draws the screen
4 · effects
Cleanup, then effect
previous cleanup() ← only on a re-runeffect()React first calls your component to get JSX (render), then updates the real DOM (commit), the browser draws it (paint), and then your effect runs. So the user sees the UI first and the effect never slows down that first paint.
import { useEffect, useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}document.title lives outside React, so changing it is a side effect. The [count] says: "run this again whenever count changes".
The dependency array decides how often
| You write | The effect runs | Typical use |
|---|---|---|
useEffect(fn) | After every render | Rare. Usually a mistake. |
useEffect(fn, []) | After the first render only | Fetch once, subscribe once |
useEffect(fn, [a, b]) | After the first render, then whenever a or b changed | Re-fetch when id changes |
React compares each dependency with its value from the last render using Object.is (basically ===). If nothing changed, the effect is skipped.
Try all three below. Notice that "Re-render only" runs a no-array effect even though nothing it cares about changed.
When does my effect run?
Try itdependency array
<StrictMode> in development
useEffect(() => {log("effect runs")return () => log("cleanup")}, [count])- renderrender #1 · count = 0
- paintDOM updated, screen painted
- effecteffect runs
Cleanup: undo what you started
If your effect starts something, return a function that stops it:
import { useEffect, useState } from "react";
export default function Clock() {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const id = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(id); // stop the timer
}, []);
return <p>{now.toLocaleTimeString()}</p>;
}React calls the cleanup at two moments:
- Before the effect runs again, so the old timer, listener or request is stopped before a new one starts. The cleanup still sees the values from its render.
- When the component unmounts (is removed from the page).
Forget it, and intervals stack up, event listeners pile on, and old requests write into state after you've moved on.
StrictMode runs it twice (in development)
Vite's React template wraps your app in <StrictMode>. In development only, StrictMode mounts each component, immediately unmounts it, and mounts it again. Your effect goes setup → cleanup → setup.
That's a deliberate stress test. Users really do leave a page and come back, and if your cleanup doesn't undo your setup you'll get two timers or two subscriptions. StrictMode makes that bug show up on day one. In production, effects run once.
Don't
Block the second run with a flag
const didRun = useRef(false);
useEffect(() => {
if (didRun.current) return;
didRun.current = true;
startChat();
}, []);Hides the warning sign. The real bug (no cleanup) is still there.
Do
Write the cleanup
useEffect(() => {
const chat = startChat();
return () => chat.stop();
}, []);Setup, cleanup, setup now ends with exactly one chat running.
Seeing two fetches in the Network tab during development is the same thing, and it's expected. The next topic shows the cleanup for fetches.
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
