Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

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

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 funct

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("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

{status}

;
}
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 array When the effect runs Typical case
omitted After every render Rare; subscriptions that must resync constantly
[] Once after mount Global listeners, timers with no reactive input
[a] After mount and whenever a changes Fetch on id change, subscribe to an external store
[a, b] Whenever either changes Multi-input synchronization
[a?.id, b] Primitive deps avoid object identity churn Prefer primitives over objects
[obj] with a new object each render Every render Bug: memoize or destructure
Hook Timing Use for
useEffect After paint, async Data fetching, subscriptions, logging
useLayoutEffect Before paint, synchronous DOM measurement, scroll restoration
useInsertionEffect Before layout, for CSS-in-JS Injecting styles
Event handler On interaction Anything triggered by a user action
Render body During render Pure computation only — no side effects
Race condition fix Mechanism Fits
AbortController Cancels the request itself fetch, streams
ignore flag Discards the result in cleanup Libraries without cancellation
useSyncExternalStore React-managed subscription External stores
Request id / sequence check Compare latest id before setting Rapid 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

{user ? user.name : "…"}

;
}
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([]);

// 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

    {results.map((r) =>
  • {r}
  • )}
;
}

function fetchResults(q: string, _opts: { limit: number }): Promise {
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

{count}

;
}
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

connected to {roomId}

;
}

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

{total} / {computed}

;
}
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

20 ? "scrolled" : ""}>{y};
}
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

Symptom Cause Fix
Effect runs on every render Missing or unstable dependency Add primitives, memoize objects, or use []
Effect never re-runs when a value changes Value omitted from deps Add it; do not silence the lint
Old value inside the effect Stale closure over a previous render Add the dep, or use an updater function
Infinite fetch loop Effect sets state that is also a dep Depend on inputs, not outputs
async callback warning Effect returned a Promise Declare async function run() inside and call it
Race: wrong data after fast switching No cleanup AbortController or an ignore flag
Memory leak warning on unmount Subscription without cleanup Return the unsubscribe function
Layout shift on first paint useEffect measuring the DOM useLayoutEffect for measurements
Effect runs twice in development StrictMode intentional double invoke Make cleanup complete; do not disable StrictMode
State set in an effect never appears Effect depends on a value that changes each render Fix 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.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.