ReactEasy

What is the dependency array in useEffect?

The dependency array is the second argument to useEffect (and to useLayoutEffect, useMemo, useCallback). It lists every reactive value the effect reads: props, state, and values derived from them. React re-runs the effect only when one of those values changes, compared with Object.is.

Three forms

  • Omitted: run after every render.
  • []: run once after mount. Only correct if the effect reads no reactive values.
  • [a, b]: run on mount and whenever a or b changes.

The rule

Dependencies are not something you choose; they are determined by the code. If the effect reads it and it can change, it must be listed. eslint-plugin-react-hooks (exhaustive-deps rule) checks this. Lying about dependencies causes stale values and bugs.

Objects and functions as dependencies

Objects, arrays and functions created during render are new each render, so the effect re-runs every time. Fixes:

  • Move the object or function inside the effect.
  • Move it outside the component if it uses no props or state.
  • Depend on primitive fields (options.roomId) instead of the whole object.
  • Memoize with useMemo/useCallback (or let the React Compiler do it).
  • Use useEffectEvent (React 19.2) for logic that should read the latest values without re-triggering the effect.

Not needed in the array

Setter functions from useState, dispatch from useReducer, refs (useRef objects), and Effect Events (useEffectEvent) are stable.

Code example

tsx
1import { useEffect, useState } from "react";
2
3export function SearchResults({ query, pageSize }: { query: string; pageSize: number }) {
4 const [results, setResults] = useState<string[]>([]);
5
6 useEffect(() => {
7 // Options object created INSIDE the effect: no new reference each render
8 const params = new URLSearchParams({ q: query, limit: String(pageSize) });
9 let ignore = false;
10
11 fetch(`/api/search?${params}`)
12 .then((r) => r.json())
13 .then((data: string[]) => {
14 if (!ignore) setResults(data); // setResults is stable: not a dependency
15 });
16
17 return () => {
18 ignore = true; // ignore responses for an old query
19 };
20 }, [query, pageSize]); // every reactive value the effect reads
21
22 return <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>;
23}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app