Sub topic 6
Dependency arrays and how React compares them
This chapter assumes you know function components, useState and useEffect, and that objects, arrays and functions are reference values in JavaScript. Earlier chapters covered referential equality and why unstable props defeat memo. Here you will see how React decides whether a hook should run again.
What a dependency array is
Hooks such as useMemo, useCallback and useEffect take a second argument, an array of values the callback reads. React stores that array from the previous render. On the next render it compares the new array to the stored one. If nothing changed, React reuses the previous result (or skips the effect). If anything changed, it runs the callback again.
const total = useMemo(() => price * quantity, [price, quantity]);Here total is recalculated only when price or quantity changes.
How the comparison works
React compares the arrays item by item, in order, using Object.is. It does not look inside objects. Object.is behaves like === with two differences: NaN equals NaN, and +0 is not equal to -0.
| Previous value | New value | Same? |
|---|---|---|
| `5` | `5` | Yes |
| `'a'` | `'a'` | Yes |
| `{ id: 1 }` | `{ id: 1 }` (new literal) | No |
| `[1, 2]` | `[1, 2]` (new literal) | No |
| `fn` (same reference) | `fn` | Yes |
| `NaN` | `NaN` | Yes |
Primitives compare by value. Objects, arrays and functions compare by reference, so two literals with identical contents are different values.
A dependency that changes every render
The most common error is a dependency that is recreated on every render. The cache never hits.
import { useMemo } from 'react';
function Results({ items, query }) {
// Broken: `filters` is a new object each render, so useMemo reruns every time.
const filters = { query, limit: 10 };
const visible = useMemo(
() => items.filter((i) => i.name.includes(filters.query)).slice(0, filters.limit),
[items, filters]
);
return <ul>{visible.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
}The fix is to depend on the primitives, not the object that wraps them.
import { useMemo } from 'react';
function Results({ items, query }) {
const limit = 10;
const visible = useMemo(
() => items.filter((i) => i.name.includes(query)).slice(0, limit),
[items, query]
);
return <ul>{visible.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
}limit is a constant declared inside the component, but it is a primitive, so it never causes a mismatch. Because it is a constant, the linter does not require it in the array.
Rules for correct arrays
- List every reactive value the callback reads. Reactive values are props, state, and anything declared in the component body.
- Do not list values defined outside the component, such as module-level constants or imports. They never change.
- Do not leave out a dependency to "stop" a callback from rerunning. The callback will then read stale values from an old render.
- Prefer primitives over objects when you have the choice.
Install eslint-plugin-react-hooks and enable react-hooks/exhaustive-deps. It reports missing and unnecessary dependencies.
Three forms compared
| Form | When it runs or recomputes |
|---|---|
| No array: `useEffect(fn)` | After every render |
| Empty array: `useMemo(fn, [])` | Once, on the first render |
| Listed values: `useMemo(fn, [a, b])` | When `a` or `b` changes by `Object.is` |
Exercise
A component declares const config = { theme } in its body and passes [config] as the dependency array to useMemo. The theme string rarely changes, yet the memoized calculation runs on every render. Why, and how do you fix it?
Show answer
config is a new object on every render, and React compares dependencies with Object.is, which checks references for objects. The new reference never equals the old one, so the callback always reruns. Fix it by depending on the primitive instead: use [theme] and read theme inside the callback. Alternatively, wrap config in its own useMemo with [theme].