React · Lesson 3
Effects
What useEffect is for (keeping a component in sync with something outside React) and what it isn't for, dependency arrays and Object.is, cleanup order, Strict Mode's double run, race-free data fetching, useLayoutEffect, and refs.
In short
- Effects sync with systems outside React
- Cleanup undoes setup; it runs before each re-run
- Dependencies are compared with
Object.is - Guard fetches with
ignoreandAbortController - No external system? You probably don't need an effect
Rendering must be pure: take props and state, return UI. But real components also have to talk to the world outside React: open a WebSocket, subscribe to a store, start a timer, call an API, measure the DOM, set up a chart library. That's what effects are for. They run after React has updated the DOM, and they keep something external in sync with your props and state.
Effects are also where most React bugs live: requests that fire twice, responses that arrive in the wrong order, subscriptions that leak, intervals that show stale numbers, and render loops. And a lot of effects shouldn't exist at all. This lesson covers how effects run, how to write them correctly, and when to use something else.
The shape of an effect
import { useEffect, useState } from 'react';
export function ChatRoom({ roomId, serverUrl }: { roomId: string; serverUrl: string }) {
const [messages, setMessages] = useState<string[]>([]);
useEffect(() => {
const connection = createConnection(serverUrl, roomId); // setup: start synchronizing
const stop = connection.on('message', (text) => setMessages((m) => [...m, text]));
connection.connect();
return () => { // cleanup: stop synchronizing
stop();
connection.disconnect();
};
}, [serverUrl, roomId]); // dependencies: re-sync when these change
return <MessageList messages={messages} />;
}
- Setup runs after the component mounts, once React has committed the DOM (and usually after the browser has painted).
- When a re-render changes a dependency, React runs the cleanup of the previous effect, with the old values,
then the setup again with the new ones. Switching from room
generaltotraveldisconnects fromgeneralfirst. - On unmount, React runs the cleanup one last time.
Think "keep the connection in sync with roomId", not "run this on mount". If the cleanup exactly undoes the setup,
it doesn't matter how often React re-runs the effect: the external system always ends up in the right state.
Dependencies are compared with Object.is
| Second argument | The effect runs |
|---|---|
| none | after every render |
[] | once after mount (cleanup on unmount) |
[a, b] | after mount, and after any render where a or b changed |
"Changed" means !Object.is(previous, next), checked dependency by dependency. That's fine for strings and numbers, but
objects, arrays and functions created during render are new every render:
// Two renders of the same component with the same props. What React compares, dependency by dependency:
const render1 = { roomId: 'general', options: { serverUrl: 'https://chat.example' }, onMessage: (t: string) => t };
const render2 = { roomId: 'general', options: { serverUrl: 'https://chat.example' }, onMessage: (t: string) => t };
console.log('roomId same?', Object.is(render1.roomId, render2.roomId));
console.log('options same?', Object.is(render1.options, render2.options)); // a new object each render
console.log('onMessage same?', Object.is(render1.onMessage, render2.onMessage)); // a new function each render
console.log('NaN same?', Object.is(NaN, NaN), '| 0 and -0 same?', Object.is(0, -0));
So useEffect(..., [options]) with an inline options object reconnects after every render. Fixes, best first:
- Create the object inside the effect, and depend on the primitives it's built from (
[serverUrl, roomId]). - Move constants out of the component entirely.
- Depend on the fields you use:
[options.serverUrl]. - If a parent passes the object or callback, memoize it there with
useMemo/useCallback. (With the React Compiler, the parent's objects and callbacks are memoized for you, but fixes 1 to 3 still make clearer code.) - For a callback the effect calls but shouldn't re-run for (like
onMessagefor logging), useuseEffectEvent(stable since React 19.2) or keep the latest callback in a ref (below).
import { useEffect, useEffectEvent } from 'react';
export function ChatRoom({ roomId, onMessage }: { roomId: string; onMessage: (text: string) => void }) {
const handleMessage = useEffectEvent((text: string) => onMessage(text)); // always calls the latest onMessage
useEffect(() => {
const connection = createConnection(roomId);
const stop = connection.on('message', (text) => handleMessage(text));
connection.connect();
return () => {
stop();
connection.disconnect();
};
}, [roomId]); // a new onMessage doesn't reconnect; an Effect Event is never a dependency
return null;
}
Never lie about dependencies to make an effect run less. The react-hooks/exhaustive-deps lint rule lists every reactive
value the effect reads. If the list causes too many runs, change the code so the effect needs fewer values. Don't
silence the rule: a missing dependency is a stale value waiting to happen. Exercise 1 builds the comparison.
Cleanup order
For one commit, React runs all the cleanups of effects that are about to re-run (or unmount) before it runs any new setup. Within a component, effects run in the order they're declared, and children's effects run before their parent's, because children finish rendering first:
import { useEffect } from 'react';
function Child() {
useEffect(() => { log('child setup'); return () => log('child cleanup'); });
return null;
}
function Parent() {
useEffect(() => { log('parent setup'); return () => log('parent cleanup'); });
return <Child />;
}
// Mount: child setup, parent setup
// Re-render: child cleanup, parent cleanup, child setup, parent setup
So a child can rely on its parent's effect from the previous render having been cleaned up before its new setup runs, but not on the parent's new setup having run yet. If a child needs something the parent sets up, pass it down instead. When a whole subtree unmounts (or Strict Mode simulates that), the cleanup order flips: the parent's cleanups run before its children's.
Strict Mode runs your effects twice
In development, <StrictMode> mounts each component, immediately simulates an unmount (running every cleanup),
then mounts it again: setup, cleanup, setup. Production runs setup once. The point is to prove your cleanup works:
- A chat connection with a correct cleanup connects, disconnects, connects: one open connection. Without a cleanup you'd see two, and that's the leak you would have shipped.
- A fetch effect fires twice in development. With an
AbortControllercleanup, the first request is cancelled. - Don't "fix" it with a
useRefflag that skips the second run. That hides a real bug (the same thing happens on fast route changes) and breaks React features that rely on remounting, like<Activity>(stable since React 19.2). An<Activity mode="hidden">boundary keeps its children's state but runs their effect cleanups, and runs the setups again when it's shown.
Strict Mode also calls component functions, state initializers, updaters and reducers twice, to catch impure code. Since React 19 it gives every callback ref the same treatment as an effect: attach, cleanup, attach.
Fetching data without races
When userId changes from 1 to 2, the request for user 1 may still be in flight. If it answers after user 2's, the
screen shows the wrong user. The cleanup has to make the old request harmless:
import { useEffect, useState } from 'react';
export function UserCard({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
let ignore = false; // for code that can't be cancelled
const controller = new AbortController(); // for code that can (fetch, axios, most SDK clients)
setError(null);
fetchUser(userId, { signal: controller.signal })
.then((u) => { if (!ignore) setUser(u); })
.catch((e: unknown) => { if (!ignore) setError(e instanceof Error ? e : new Error(String(e))); });
return () => {
ignore = true;
controller.abort();
};
}, [userId]);
return error ? <ErrorBox error={error} /> : user ? <Profile user={user} /> : <Spinner />;
}
Here's the race in plain TypeScript, with and without the ignore flag:
const delays: Record<string, number> = { a: 40, ab: 10 }; // the request for "a" is slower
const search = (q: string) => new Promise<string>((resolve) => setTimeout(() => resolve(`results for "${q}"`), delays[q]));
let naive = '';
let safe = '';
function effect(query: string): () => void { // what the effect body does
let ignore = false;
search(query).then((r) => {
naive = r; // without the flag: the last response to ARRIVE wins
if (!ignore) safe = r; // with the flag: only the current effect may update
});
return () => { ignore = true; };
}
const cleanupA = effect('a');
cleanupA(); // the user typed "b": React cleans up the old effect...
effect('ab'); // ...and runs the new one
setTimeout(() => console.log('naive shows', naive, '| safe shows', safe), 60);
- The
ignoreflag guarantees a stale response can't set state, even when the API ignores cancellation. - Aborting also stops the network work and frees the server. Use both. Exercise 4 builds this effect.
- In a real app, reach for a data library (TanStack Query, RTK Query) or your framework's loaders. They handle races,
caching, deduplication and retries. The TypeScript track's "Latest-only async calls" exercise builds the same guard as
a reusable wrapper, and RxJS's
switchMapis the Angular answer to the same problem.
You might not need an effect
An effect is for synchronizing with something outside React. If there's no external system, there's usually a simpler and faster way:
| Instead of an effect that... | Do this |
|---|---|
| computes a value from props or state and stores it | compute it during render (useMemo if it's expensive) |
| resets state when a prop changes | give the component a key |
| runs because the user did something (submit, click, buy) | put the logic in the event handler |
| sets state that triggers another effect that sets state | compute everything in one event handler or reducer |
tells the parent about a state change (onChange(value)) | call onChange in the same handler that sets the state |
| subscribes to an external store | useSyncExternalStore (see the Context topic) |
import { useEffect, useState } from 'react';
function CheckoutForm({ cart }: { cart: Cart }) {
const [submitted, setSubmitted] = useState(false);
// ✗ An effect reacting to a flag that an event set:
useEffect(() => {
if (submitted) {
void api.placeOrder(cart);
showToast('Order placed');
}
}, [submitted, cart]);
// ✓ The user clicked, so do it in the click handler:
async function handlePlaceOrder() {
await api.placeOrder(cart);
showToast('Order placed');
}
return <button onClick={handlePlaceOrder}>Place order</button>;
}
The effect version also has a bug: it re-runs whenever cart changes while submitted is true, placing another order.
useLayoutEffect
useLayoutEffect has the same signature, but runs synchronously after React updates the DOM and before the browser
paints. All layout effects (cleanups, then setups) run before any normal effect of the same commit. Use it when you must
measure the DOM and adjust before the user sees anything, for example positioning a tooltip:
import { useLayoutEffect, useRef, useState } from 'react';
export function Tooltip({ anchor, text }: { anchor: DOMRect; text: string }) {
const ref = useRef<HTMLDivElement>(null);
const [top, setTop] = useState(anchor.bottom + 8);
useLayoutEffect(() => {
const height = ref.current!.getBoundingClientRect().height;
const below = anchor.bottom + 8;
setTop(below + height > window.innerHeight ? anchor.top - height - 8 : below); // flip above if it doesn't fit
}, [anchor]);
return <div ref={ref} className="tooltip" style={{ top }}>{text}</div>;
}
With useEffect the tooltip would paint in the wrong place for one frame and then jump. The cost: layout effects block
painting, so keep them short, and default to useEffect for everything else. They don't run during server rendering.
Refs
useRef(initial) returns a plain { current } object that is the same object on every render. Changing current does
not trigger a render. That makes refs the place for values that effects and event handlers need but the screen doesn't:
import { useEffect, useRef } from 'react';
export function SearchInput({ onSearch, autoFocus }: { onSearch: (q: string) => void; autoFocus: boolean }) {
const inputRef = useRef<HTMLInputElement>(null); // a DOM node
const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); // a timer id
const onSearchRef = useRef(onSearch); // the latest callback
useEffect(() => { onSearchRef.current = onSearch; }); // keep it current after every render
useEffect(() => { if (autoFocus) inputRef.current?.focus(); }, [autoFocus]);
useEffect(() => () => clearTimeout(timerRef.current), []); // clear the timer on unmount
return (
<input
ref={inputRef}
onChange={(e) => {
const q = e.target.value;
clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => onSearchRef.current(q), 300); // always the latest onSearch
}}
/>
);
}
- DOM refs:
useRef<HTMLInputElement>(null)plusref={inputRef}. React setscurrentwhen the element mounts and back tonullwhen it unmounts. Use them for focus, scrolling, measuring and third-party widgets. - Callback refs (
ref={(node) => ...}) run when the node attaches. Since React 19 they can return a cleanup function, which React calls when the node detaches. Exercise 3 merges several refs into one, the way design-system components combine their own ref with the caller's. - Don't read or write
ref.currentduring render (except to initialize it once). Render must be pure, and a ref changes without React knowing, so the output would depend on timing. - The latest-value ref above lets a long-lived timer or subscription call the newest callback without re-subscribing.
useEffectEventis the built-in version of that pattern for code an effect sets up. It may only be called from inside effects (not from event handlers, and not passed to children), so a timer started inonChange, as above, still uses a ref.
Common mistakes
- Missing cleanup: intervals, listeners and subscriptions that outlive the component.
setInterval(() => setSeconds(seconds + 1), 1000)with[]dependencies: it reads thesecondsfrom the first render forever, so the display sticks at 1. UsesetSeconds((s) => s + 1).- An object or function in the dependency array that's recreated every render, causing a re-run (or a loop if the effect sets state).
- Fetching without an
ignoreflag orAbortController. - Using an effect for derived data, for resetting state, or for logic that belongs in an event handler.
- Adding a ref flag to stop Strict Mode's second run instead of writing a cleanup.
In a real codebase
Side note
- Most server data comes from TanStack Query or RTK Query hooks, so hand-written fetch effects are rare.
- Effects remain for subscriptions (WebSocket, Server-Sent Events,
BroadcastChannel), browser APIs (ResizeObserver,IntersectionObserver,matchMedia), timers, analytics and integrating non-React widgets (maps, charts, rich-text editors). - Shared connections, like one WebSocket connection used by many components, are wrapped in a module or context that counts subscribers, so Strict Mode and quick navigation don't reconnect every time. Exercise 6 builds that.
- If you know Angular:
useEffectwith a cleanup is close to an Angular signaleffect()withonCleanup, or a subscription closed bytakeUntilDestroyed(). The big difference is that React effects list their dependencies explicitly, while Angular'seffect()tracks the signals it reads.
The exercises
- Dependency check: decide whether an effect should re-run, with
Object.issemantics. - Chat room effect: a setup and cleanup that survive room changes and Strict Mode.
- mergeRefs: combine object refs and callback refs, including React 19 ref cleanups.
- Race-free fetch effect: an
ignoreflag plus anAbortController, keeping the previous data while loading. - An effects runtime:
useEffect,useLayoutEffectanduseRefwith React's ordering and Strict Mode. - Shared connections: reference-counted connections with a close delay, so remounts don't reconnect.
Practise this lesson
In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app