Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React useEffect: Dependency Arrays, Cleanup Functions, and Race Conditions

Effects synchronise with the outside world, and cleanup is what makes that safe. Dependency rules, abort controllers and the loops that follow from unstable deps.

~5 min readReact
#React#Hooks#Effects
3D illustration of a component lifecycle synchronised with AbortController fetch cancellation

Quick Summary

useEffect synchronizes a component with something outside React: a subscription, the DOM, a network request, a timer. It is not a lifecycle hook and it is not the place for derived state. The effect function runs after the browser paints, and the optional cleanup runs before the next execution of the same effect and once on unmount.

The dependency array is compared item by item with Object.is. [] means "never re-run", [a, b] means "re-run when either changes", and omitting the array means "run after every render". Every reactive value used inside the effect belongs in the array — that is what the react-hooks/exhaustive-deps lint enforces, and disabling it is how stale closures become production bugs.

Race conditions are the second half of the story. A fetch started on one render can resolve after a newer fetch has already come back, overwriting fresh data with stale data. React's answer is cleanup: return a function that aborts the request or ignores its result, and React guarantees it runs before the next effect.

Basic Syntax & Signature

tsx
import { useEffect, useState } from "react"; export function Status({ userId }: { userId: string }) { const [status, setStatus] = useState<string>("idle"); // Runs once on mount; cleanup runs on unmount. useEffect(() => { const id = setInterval(() => setStatus("tick"), 1000); return () => clearInterval(id); }, []); // Runs on mount and whenever userId changes. useEffect(() => { if (!userId) return; const controller = new AbortController(); async function run() { try { const res = await fetch(`/api/status/${userId}`, { signal: controller.signal, }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = (await res.json()) as { state: string }; setStatus(data.state); } catch (err) { if (err instanceof DOMException && err.name === "AbortError") return; setStatus("error"); } } run(); return () => controller.abort(); }, [userId]); return <p>{status}</p>; }

The type signatures, which explain why the callback cannot be async:

ts
function useEffect( setup: () => void | (() => void), deps?: readonly unknown[] ): void; // Not valid: an async function returns a Promise, not a cleanup function. // useEffect(async () => { ... }, []);

useLayoutEffect has the same signature and runs synchronously before the browser paints — use it only for measurements that must happen before the user sees the frame.

Key Comparison Table

Dependency arrayWhen the effect runsTypical case
omittedAfter every renderRare; subscriptions that must resync constantly
[]Once after mountGlobal listeners, timers with no reactive input
[a]After mount and whenever a changesFetch on id change, subscribe to an external store
[a, b]Whenever either changesMulti-input synchronization
[a?.id, b]Primitive deps avoid object identity churnPrefer primitives over objects
[obj] with a new object each renderEvery renderBug: memoize or destructure
HookTimingUse for
useEffectAfter paint, asyncData fetching, subscriptions, logging
useLayoutEffectBefore paint, synchronousDOM measurement, scroll restoration
useInsertionEffectBefore layout, for CSS-in-JSInjecting styles
Event handlerOn interactionAnything triggered by a user action
Render bodyDuring renderPure computation only — no side effects
Race condition fixMechanismFits
AbortControllerCancels the request itselffetch, streams
ignore flagDiscards the result in cleanupLibraries without cancellation
useSyncExternalStoreReact-managed subscriptionExternal stores
Request id / sequence checkCompare latest id before settingRapid successive queries

Practical Edge Cases & Deep Dives

1. The fetch race, and why cleanup is the fix

tsx
function Profile({ id }: { id: string }) { const [user, setUser] = useState<{ name: string } | null>(null); // Broken: the slow first request can overwrite the fast second one. useEffect(() => { fetch(`/api/users/${id}`) .then((r) => r.json()) .then((data) => setUser(data)); }, [id]); // Correct: the cleanup discards the stale response. useEffect(() => { let ignore = false; fetch(`/api/users/${id}`) .then((r) => r.json()) .then((data) => { if (!ignore) setUser(data); }); return () => { ignore = true; }; }, [id]); return <p>{user ? user.name : "…"}</p>; }

Switching id from 1 to 2 mounts the second effect before the response for 1 arrives. Without the flag, the older response applies to the newer id and the page shows the wrong user until something else triggers a render. The ignore closure works because each effect invocation captures its own ignore variable.

2. Infinite loops from unstable dependencies

tsx
function Search({ query }: { query: string }) { const [results, setResults] = useState<string[]>([]); // Infinite: `options` is a new object every render. const options = { limit: 10 }; useEffect(() => { fetchResults(query, options).then(setResults); }, [query, options]); // Fixed: depend on primitives, or memoize the object. useEffect(() => { fetchResults(query, { limit: 10 }).then(setResults); }, [query]); return <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>; } function fetchResults(q: string, _opts: { limit: number }): Promise<string[]> { return Promise.resolve(q ? [`${q}-1`] : []); }

Objects, arrays and inline functions are recreated on every render, so Object.is never matches. Depend on the primitive pieces (limit, query) instead. When the effect truly needs a function from props, wrap it in useCallback in the parent — or move the function inside the effect if nothing outside it calls the function.

3. setInterval and the stale closure

tsx
function Ticker() { const [count, setCount] = useState(0); // Wrong: the interval captures count === 0 forever. // useEffect(() => { // const id = setInterval(() => setCount(count + 1), 1000); // return () => clearInterval(id); // }, []); // Right: the updater form reads the latest queued value. useEffect(() => { const id = setInterval(() => setCount((c) => c + 1), 1000); return () => clearInterval(id); }, []); return <p>{count}</p>; }

Adding count to the dependency array "fixes" this and destroys it at the same time: the interval is cleared and recreated every second. The functional updater is the correct answer whenever the new state depends on the old one and the effect must stay mounted.

4. StrictMode double invocation in development

tsx
function Chat({ roomId }: { roomId: string }) { useEffect(() => { const connection = createConnection(roomId); connection.connect(); // This cleanup runs immediately after the first mount in StrictMode dev, // then the effect runs again. Idempotent cleanup is mandatory. return () => connection.disconnect(); }, [roomId]); return <p>connected to {roomId}</p>; } function createConnection(roomId: string) { return { connect: () => console.log("connect", roomId), disconnect: () => console.log("disconnect", roomId), }; }

React 18 StrictMode mounts, unmounts, and remounts every component once in development to surface exactly this class of bug: an effect that connects but never disconnects leaks a socket in production after every navigation. Production builds do not double-invoke, so a leak found this way is real.

5. Effects are for external systems, not for derived state

tsx
type Item = { id: number; price: number; qty: number }; function Cart({ items }: { items: Item[] }) { const [total, setTotal] = useState(0); // Wrong: an extra render, and a flash of the previous total. useEffect(() => { setTotal(items.reduce((sum, i) => sum + i.price * i.qty, 0)); }, [items]); // Right: compute during render; no state, no effect, no flash. const computed = items.reduce((sum, i) => sum + i.price * i.qty, 0); // Memoized only when the computation is expensive. // const computed = useMemo(() => expensive(items), [items]); return <p>{total} / {computed}</p>; }

Anything derivable from props or state during render should be computed during render. The effect version renders twice for every input change, and worse, between the two renders the UI shows a value that cannot exist.

6. Subscribing to an external store correctly

tsx
import { useSyncExternalStore } from "react"; function subscribe(callback: () => void) { const onScroll = () => callback(); window.addEventListener("scroll", onScroll); return () => window.removeEventListener("scroll", onScroll); } function useScrollY(): number { return useSyncExternalStore( subscribe, () => window.scrollY, () => 0, // server snapshot ); } function Header() { const y = useScrollY(); return <header className={y > 20 ? "scrolled" : ""}>{y}</header>; }

useSyncExternalStore exists because a manual useEffect subscription can tear: two components reading the same store can render with different values in one commit. For browser APIs, third-party state containers, and anything with a subscribe function, this hook is the supported pattern; the effect-based version is a fallback for stores that only offer an event emitter.

Common Compilation/Runtime Mistakes

SymptomCauseFix
Effect runs on every renderMissing or unstable dependencyAdd primitives, memoize objects, or use []
Effect never re-runs when a value changesValue omitted from depsAdd it; do not silence the lint
Old value inside the effectStale closure over a previous renderAdd the dep, or use an updater function
Infinite fetch loopEffect sets state that is also a depDepend on inputs, not outputs
async callback warningEffect returned a PromiseDeclare async function run() inside and call it
Race: wrong data after fast switchingNo cleanupAbortController or an ignore flag
Memory leak warning on unmountSubscription without cleanupReturn the unsubscribe function
Layout shift on first paintuseEffect measuring the DOMuseLayoutEffect for measurements
Effect runs twice in developmentStrictMode intentional double invokeMake cleanup complete; do not disable StrictMode
State set in an effect never appearsEffect depends on a value that changes each renderFix deps; or compute during render

The deepest trap is the one that produces no error: an effect whose dependency array is correct but whose cleanup is incomplete. React calls cleanup before the next run and on unmount, so any resource acquired in the effect — listener, timer, socket, abort controller, subscription — needs a matching release. If you cannot write the cleanup, the thing you are doing probably belongs in an event handler instead.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.