Skip to content
Tutorials Center
My learning

Topics

React Reference ยท Effect and Ref Hooks

React useEffect dependency array

Reference for the useEffect dependency array: what no array, an empty array and a list of values mean, how React compares them, and how to fix stale-value bugs.

The second argument of useEffect is the dependency array. It tells React which values the effect reads, so React can skip re-running the effect when none of them changed. There are three forms, and each has a different meaning.

The array is not a trigger list you pick freely. It is a description of what the effect code uses. If the effect reads roomId, then roomId belongs in the array, because the effect must run again when it changes.

JSX
useEffect(effect);             // after every render
useEffect(effect, []);         // after the first render only
useEffect(effect, [a, b]);     // after the first render and whenever a or b changed

Try it

Three forms side by side

Click a: all three log. Click b: only the effect without an array logs.

Objects in the array change every render

Type a few letters: the object effect runs on every keystroke, the primitive one only on mount. The fix is to depend on the primitives (limit) or to create the object inside the effect.

Syntax

JSX
useEffect(setup, [dep1, dep2, ...]);
Form When the effect runs
omitted After every render.
[] After the first render (and again in the StrictMode development check). Cleanup runs on unmount.
[a, b] After the first render, then after any render in which a or b differs from the previous render (compared one by one with Object.is).

Rules for the array: it must have a constant length and order between renders; write it inline so linters can check it; pass only values that appear in the effect.

Usage notes

  • Reactive values are props, state and anything declared inside the component body (including functions and objects). Module-level constants and ref.current are not reactive and do not belong in the array. Setters from useState and dispatch are stable and may be left out.
  • Never lie to the array. Leaving out a value the effect uses produces stale closures: the effect keeps seeing old props and state. Fix the effect, not the list.
  • Objects and functions created during render are new on every render. Move them inside the effect, hoist them out of the component, or memoize them with useMemo / useCallback.
  • Too many re-runs? Use an updater (setX(x => x + 1)) to drop a state dependency, or read the latest values without re-triggering via useEffectEvent.
  • [] is not "do it once". In development StrictMode runs it twice, and a component that remounts runs it again. It means "does not depend on any reactive value".
  • Comparing: Object.is(NaN, NaN) is true, Object.is(0, -0) is false. Mutating an object does not change its identity, so a mutated dependency will not re-run the effect.
  • Layout and insertion effects use the same array rules.