Lesson 13 of 37Effects and beyond
useEffect
Keep a component in sync with timers, subscriptions, and the DOM, and know when you do not need an effect at all.
Everything you have built so far lives inside React: state changes, React re-renders, the screen updates. Real apps also talk to things React does not control: timers, browser events, a chat server, a third-party map widget. useEffect is how a component keeps those outside systems in step with its state, and misusing it is the single most common source of React bugs in code review.
Effects synchronize with the outside world
A component's job is to return JSX for the current props and state. That work must be pure: no timers started, no network calls, no DOM poking. An effect is code that runs after React has updated the screen, so it can safely reach outside.
useEffect(() => {
// setup: connect to something outside React
return () => {
// cleanup: disconnect from it
};
}, [dependencies]);Think of it less as "run this on mount" and more as "keep this outside thing matching my state". Here a clock starts an interval when it appears and stops it when it disappears. Open the console under the preview and toggle it a few times.
Without the cleanup, every hide and show would leave another interval running in the background, still calling setNow on a component that no longer exists. That is a memory leak: work and memory that never get released.
When effects run
React works in phases. It calls your component (the render phase), writes the changes to the real DOM (the commit phase), lets the browser paint, and only then runs your effects.
A click calls a state setter. React schedules a re-render.
A dependency of an effect changes. Put what React does in order.
- Tap the steps below in the right order.
The dependency array
The second argument tells React when to re-synchronize.
| You write | The effect runs |
|---|---|
useEffect(fn) | after every render |
useEffect(fn, []) | once after the first render (cleanup on unmount) |
useEffect(fn, [roomId]) | after the first render and whenever roomId changes |
React compares each dependency with its previous value using Object.is. Every reactive value the effect reads (props, state, and anything computed from them) belongs in the array. The react-hooks/exhaustive-deps lint rule checks this for you, and you should treat its warnings as bugs, not noise.
function ChatRoom({ roomId }: { roomId: string }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // switching rooms disconnects the old one, connects the new one
}roomId but the array is []. What happens when the user switches from room general to room random?useEffect(() => {
const c = createConnection(roomId);
c.connect();
return () => c.disconnect();
}, []);Cleanup: timers, listeners, subscriptions
Any effect that starts something should return a function that stops it. The pairs are always symmetrical: setInterval/clearInterval, addEventListener/removeEventListener, subscribe/unsubscribe, connect/disconnect.
Move your pointer over the preview. The listener is attached to window once and removed when the tracker is switched off.
Notice handleMove is defined inside the effect. removeEventListener only removes the exact same function object you added, so setup and cleanup must share it.
StrictMode runs your effect twice in development
Most projects wrap the app in <StrictMode>. In development only, React then mounts every component, immediately unmounts it, and mounts it again. Your effect runs setup, cleanup, setup.
This is deliberate. Users really do unmount and remount components (navigating away and back, toggling tabs), and a missing cleanup shows up as a bug much later. StrictMode forces that path on the first load so you see it immediately. In production builds it runs once.
This component mounts inside <StrictMode> during npm run dev. What is logged?
function Chat() {
useEffect(() => {
console.log("connect");
return () => console.log("disconnect");
}, []);
return <p>Chat</p>;
}You might not need an effect
Effects are an escape hatch for external systems. Two patterns cause most of the misuse.
1. Deriving data. If a value can be computed from props or state, compute it during render. Storing it in state and syncing with an effect costs an extra render and can show stale data for a frame.
const [items, setItems] = useState<Item[]>([]);
const [visible, setVisible] = useState<Item[]>([]);
useEffect(() => {
setVisible(items.filter((i) => !i.done));
}, [items]);const [items, setItems] = useState<Item[]>([]);
const visible = items.filter((i) => !i.done); // computed every render2. Reacting to a user action. If code should run because the user did something, put it in the event handler. An effect runs because the component rendered, and it cannot tell why.
// Avoid: fires on every render where submitted is true, including after a refresh
useEffect(() => {
if (submitted) sendAnalytics("signup");
}, [submitted]);
// Prefer: fires exactly once, when the user clicks
function handleSubmit() {
setSubmitted(true);
sendAnalytics("signup");
}useEffect? Pick all that apply.None picked yet
Race conditions and the ignore flag
Fetching in an effect has a trap. If userId changes from 1 to 2, two requests are in flight. If the first one is slower, it arrives last and overwrites the correct data. The fix is a flag that the cleanup flips:
useEffect(() => {
let ignore = false;
fetchUser(userId).then((user) => {
if (!ignore) setUser(user);
});
return () => {
ignore = true;
};
}, [userId]);When userId changes, React runs the old cleanup first, so the stale request's ignore becomes true and its result is dropped. The data-fetching lesson builds on this, and in real apps a library usually handles it for you.
Match each setup to its cleanup.
Practice
Stopwatch with an interval
Build a stopwatch that counts in tenths of a second.
- An
<output>shows the elapsed time with one decimal:0.0,0.1,0.2… - Start begins counting (one tick every 100 ms).
- Stop freezes the time.
- Reset stops the watch and sets it back to
0.0.
Pressing Start twice must not make the watch run twice as fast, and no interval may keep running after Stop or Reset. Keep the time in state and let an effect own the interval.
Keyboard listener with cleanup
Count key presses anywhere on the page.
- A paragraph shows
Keys pressed: 0, thenKeys pressed: 1, and so on. - Another paragraph shows
Last key: noneuntil a key is pressed, then the key, for exampleLast key: a. - A checkbox labelled Listening starts checked. While it is unchecked, key presses are ignored.
Listen with window.addEventListener("keydown", …) inside an effect. Unchecking and checking the box again must not leave two listeners attached (one key press must count once).
- effect
- Code that runs after React commits a render, used to synchronize a component with something outside React.
- dependency array
- The second argument to
useEffect. React re-runs the effect when any value in it changes (compared withObject.is). - cleanup function
- The function an effect returns. React calls it before re-running the effect and when the component unmounts.
- StrictMode double run
- In development, React mounts, unmounts, and remounts components so missing cleanups surface immediately.
- derived state
- A value computed from props or state during render. It should not be stored in state or synced with an effect.
- race condition
- Two async results arriving in an unexpected order, so stale data overwrites fresh data. Fixed with an
ignoreflag in the cleanup.