Sub topic 6
Dependency arrays and how React compares them
This chapter assumes you know function components, JSX, useState and useEffect, and that objects, arrays and functions in JavaScript are reference values. Earlier chapters covered why components re-render and what referential equality means. Here you will see how React decides whether a hook should run again, and which mistakes cause stale values or needless work.
What a dependency array is
Several hooks take a second argument: an array of values the hook reads from the component's scope. This array is the dependency array. useEffect, useLayoutEffect, useMemo, useCallback and useImperativeHandle all use one.
useEffect(() => {
document.title = `Hello, ${name}`;
}, [name]);The array answers one question for React: "Has anything this function depends on changed since the last render?" If nothing changed, React skips the work. For useEffect, the work is running the effect. For useMemo and useCallback, the work is recomputing the value or creating a new function.
The array does not control when your component renders. It only controls what the hook does during a render that is already happening.
How React compares the values
On each render, React compares the new dependency array to the one saved from the previous render. It compares item by item, in order, with Object.is. If every item is the same, the hook reuses its previous result. If any item differs, the hook runs again.
Object.is behaves like === with two exceptions:
| Comparison | `===` | `Object.is` |
|---|---|---|
| `NaN` and `NaN` | `false` | `true` |
| `0` and `-0` | `true` | `false` |
| Two different `{}` literals | `false` | `false` |
| The same object reference twice | `true` | `true` |
For primitives (strings, numbers, booleans, null, undefined), the comparison is by value. For objects, arrays and functions, it is by reference. Two objects with identical contents are still different if they were created separately.
import { useEffect, useState } from 'react';
export function Logger({ user }) {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('effect ran for', user.name);
}, [user]);
return <button onClick={() => setCount(count + 1)}>Clicked {count}</button>;
}Whether this effect runs after each click depends on the parent. If the parent passes the same user reference every time, the effect runs once. If the parent writes <Logger user={{ name: 'Ada' }} />, a new object is created whenever the parent renders, and the effect runs after every parent render.
Clicking the button only changes Logger's own state. The parent does not re-render, so user keeps the same reference and the effect stays quiet.
The three forms of the array
The shape of the second argument changes the behavior.
| Form | Meaning for `useEffect` | Meaning for `useMemo` and `useCallback` |
|---|---|---|
| No array | Runs after every render | Recomputes on every render, so it caches nothing |
| `[]` | Runs once after the first render (and cleans up on unmount) | Computes once and keeps the result for the component's lifetime |
| `[a, b]` | Runs after the first render and again whenever `a` or `b` changes | Recomputes when `a` or `b` changes |
In development with Strict Mode, React runs effects an extra time on mount to help you find missing cleanup. That extra run is not a bug in your dependency array.
The rule: list everything the function reads
A dependency array is not a list of the values you want to trigger the hook. It is a list of every reactive value the function uses. Reactive values are props, state, and anything you declare inside the component body, such as variables and functions derived from them.
Values defined outside the component, and refs from useRef (the ref object itself is stable), do not need to be listed. Setter functions returned by useState and dispatch from useReducer are also stable, so listing them is harmless but unnecessary.
The react-hooks/exhaustive-deps ESLint rule checks this for you. Keep it enabled as an error in your project.
A stale closure
If you leave out a value that the function reads, the function keeps using the value from the render where it was created.
import { useCallback, useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
// Bug: count is read but not listed, so it is always 0 here.
const logCount = useCallback(() => {
console.log('count is', count);
}, []);
return (
<>
<button onClick={() => setCount(count + 1)}>Add</button>
<button onClick={logCount}>Log</button>
</>
);
}After three clicks on "Add", clicking "Log" prints count is 0. The function closed over count from the first render and [] told React never to replace it. The fix is [count]. A new function is then created whenever count changes.
Removing a dependency the right way
Sometimes the correct list causes too many re-runs. Do not delete the dependency to silence the linter. Change the code so the value is no longer needed.
For state updates, use the updater form of the setter, which reads the latest state without a dependency:
import { useCallback, useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount((c) => c + 1);
}, []);
return <button onClick={increment}>Clicked {count}</button>;
}Here increment reads no reactive value, so [] is correct and the function stays stable.
Other options for removing a dependency:
- Move a constant object or function outside the component so it is not reactive.
- Move the object creation inside the effect or memoized function, and depend on the primitives it is built from.
- Depend on a primitive field instead of the whole object, such as
[user.id]instead of[user], when the function only readsuser.id.
Object and function dependencies
Objects and functions created during render are new on every render. If you put one in a dependency array, the hook runs on every render, which defeats the array.
import { useEffect } from 'react';
export function Room({ roomId, serverUrl }) {
// Bug: options is a new object each render.
const options = { roomId, serverUrl };
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // reconnects after every render
return <p>Room {roomId}</p>;
}
function createConnection({ roomId, serverUrl }) {
return {
connect: () => console.log('connect', serverUrl, roomId),
disconnect: () => console.log('disconnect', serverUrl, roomId),
};
}The effect reconnects on each render. The cleanest fix is to build the object inside the effect and depend on the primitives:
import { useEffect } from 'react';
export function Room({ roomId, serverUrl }) {
useEffect(() => {
const options = { roomId, serverUrl };
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId, serverUrl]);
return <p>Room {roomId}</p>;
}
function createConnection({ roomId, serverUrl }) {
return {
connect: () => console.log('connect', serverUrl, roomId),
disconnect: () => console.log('disconnect', serverUrl, roomId),
};
}Now the effect runs only when roomId or serverUrl changes. Functions follow the same logic. A function declared in the component body is a new reference each render. Move it inside the effect, move it outside the component, or wrap it in useCallback.
Edge cases and gotchas
- Mutation is invisible. React compares references, not contents. If you mutate an array with
pushand pass the same array,Object.issees no change and the hook does not re-run. Create a new array, for example[...items, newItem]. - The array length must not change. React expects the same number of items on every render. Do not build the array conditionally. A changing length produces a development warning, and the comparison is unreliable.
NaNis safe. BecauseObject.is(NaN, NaN)istrue, aNaNdependency does not cause a re-run on every render.- Refs do not trigger anything. Changing
ref.currentdoes not re-render and is not tracked. Puttingref.currentin a dependency array reads a value at render time and is usually a mistake. - A dependency is checked during render. React compares values after the render function returns, using the values from that render. A change that happens between renders is only seen on the next one.
- Effects and memoization differ in guarantees.
useEffectruns when dependencies change, and that is reliable.useMemois a performance hint. React may discard cached values in the future, for example to free memory, so your code must be correct without the cache.
Putting it together with memoization
Dependency arrays connect the earlier chapters on referential equality and React.memo. useMemo and useCallback use the same comparison to decide whether to return the old reference or a new one. A stable reference from them is what lets memo skip a child. The stability chain breaks when one dependency is itself unstable. If options depends on an object that is rebuilt each render, useMemo recomputes each render, and the child still re-renders. Fix the unstable value at its source, not at the end of the chain.
Exercise
A component declares const filters = { category }; in its body, where category is a string prop. It then calls useMemo(() => expensiveFilter(items, filters), [items, filters]). Does the memo save any work? How would you fix it?
Show answer
No. filters is a new object on every render, so Object.is finds it different each time and useMemo recomputes on every render. Fix it by depending on the primitive: create the object inside the callback and use [items, category] as the dependency array. Alternatively, wrap filters in its own useMemo with [category], but the first option is simpler.
Exercise
This function should log the latest query when called, but it always logs the first value. Why, and what is the fix?
const search = useCallback(() => console.log(query), []);
Show answer
The array is empty, so React never creates a new function after the first render, and the function keeps the query value from that render (a stale closure). Add query to the array: [query]. A new function is then created whenever query changes.
Exercise
You call items.push(newItem) and then setItems(items). A useMemo depends on [items]. Why does the memoized value not update?
Show answer
The array is mutated, but its reference stays the same. Object.is sees the same reference, so React treats the dependency as unchanged and may not even re-render. Create a new array instead, for example setItems([...items, newItem]).