Sub topic 7
Getting dependency arrays right
Prerequisites
This chapter assumes you know function components, useState, and the basics of useEffect. It also assumes you are comfortable with closures and promises. You should have read the chapter on effects and cleanup inside a hook. Here we focus on one question: what goes in the dependency array, and why.
What the array does
A dependency array is the second argument to useEffect. React compares each value in it with the value from the previous render, using Object.is. If every value is the same, React skips the effect. If any value differs, React runs the old cleanup, then runs the effect again.
The array is not a list of things you want to react to. It is a list of every reactive value that the effect reads. A reactive value is a prop, a state variable, or anything declared inside the component or hook body, including functions defined there.
An effect is a closure. It sees the values from the render in which it was created. If you leave a value out of the array, the effect keeps using an old copy of it.
import { useState, useEffect } from 'react';
// Bug: the effect reads `step`, but the array does not list it.
export function useTicker(step) {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => setCount((c) => c + step), 1000);
return () => clearInterval(id);
}, []); // stale: always uses the first `step`
return count;
}If step changes from 1 to 5, this hook keeps adding 1. The fix is to list step:
import { useState, useEffect } from 'react';
export function useTicker(step) {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => setCount((c) => c + step), 1000);
return () => clearInterval(id);
}, [step]);
return count;
}Now a change to step clears the old interval and starts a new one with the new value.
The three shapes of an array
| Form | When the effect runs | Typical use |
|---|---|---|
| No array | After every render | Rare. Syncing something that must follow each render. |
| `[]` | Once after mount, cleanup on unmount | Setup that reads no reactive values. |
| `[a, b]` | After mount, and after `a` or `b` changes | Most effects. |
An empty array is a claim: "this effect reads nothing that can change." If the claim is false, you have a stale closure.
Let the linter decide
The react-hooks/exhaustive-deps rule from eslint-plugin-react-hooks checks that your array matches what the effect reads. Treat its warnings as bugs, not style hints. Do not silence it with // eslint-disable-next-line. If the warning feels wrong, the code usually needs a different shape. The sections below show the usual ways to change it.
The dependency array does not choose what the effect reads. The code inside the effect does. To change the array, change the effect.
Reading the debounce hook
Look at the debounce hook from this tutorial's examples:
import { useState, useEffect } from 'react';
export function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}The effect reads value, delay, and setDebounced. The setter returned by useState is guaranteed stable, so React's linter knows it can be omitted. value and delay change, so they must appear. Each change cancels the pending timer through cleanup and starts a new one. That is exactly how debouncing works: only the last change within the delay window survives.
Objects, arrays, and functions as dependencies
Object.is compares objects by identity, not by contents. Two objects with the same fields are different values if they were created separately. Every render creates new object literals, new array literals, and new function expressions.
import { useEffect } from 'react';
// Bug: `options` is a new object on every render,
// so this effect runs after every render.
export function useLogger(message, level) {
const options = { level };
useEffect(() => {
console.log(message, options);
}, [message, options]);
}The effect is correct in what it lists, but it runs far too often. There are four fixes, in order of preference.
- Move the creation inside the effect. If only the effect needs the object, build it there and depend on the primitives.
- Depend on primitives. Pass
level, not an object that wraps it. - Move static values outside the component. A constant defined at module level is not reactive and needs no entry.
- Memoize with
useMemooruseCallback. Use this when the value must be shared with the caller or with other hooks.
Here is fix 1:
import { useEffect } from 'react';
export function useLogger(message, level) {
useEffect(() => {
const options = { level };
console.log(message, options);
}, [message, level]);
}Objects passed in by the caller
When a hook accepts an object or function from its caller, you do not control its identity. Consider this call:
useFetchJson(`/api/items?page=${page}`);A string is a primitive, so the hook can safely list url. If the hook instead took { url, headers }, every caller would need to memoize that object, or the effect would restart each render. This is a design reason to prefer primitive parameters. The chapter on designing parameters and return values covers this choice.
Functions as dependencies
A function declared in a component or hook body is a new value each render. If an effect calls it, the function must be in the array, and the effect restarts every render unless the function is stable.
import { useEffect, useCallback } from 'react';
export function useInterval(callback, delay) {
useEffect(() => {
const id = setInterval(callback, delay);
return () => clearInterval(id);
}, [callback, delay]);
}
// Caller
function Clock({ onTick }) {
// Without useCallback, `handleTick` is new each render
// and the interval restarts every time.
const handleTick = useCallback(() => onTick(Date.now()), [onTick]);
useInterval(handleTick, 1000);
return null;
}This works, but it pushes work onto every caller. The next chapters show two better options: return stable functions with useCallback, and read the latest callback through a ref so callers need no memoization.
If a function does not use any reactive values, move it outside the component. It then needs no entry.
Updater functions remove state dependencies
Often you list a state variable only because you read it to compute the next state. Use the functional form of the setter instead.
import { useState, useEffect } from 'react';
// Restarts the interval on every tick, because `count` changes.
export function useCounterBad() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => setCount(count + 1), 1000);
return () => clearInterval(id);
}, [count]);
return count;
}
// Runs once. The updater receives the current value.
export function useCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => setCount((c) => c + 1), 1000);
return () => clearInterval(id);
}, []);
return count;
}In the second version the effect no longer reads count, so [] is truthful. The same idea applies to useToggle: setOn((value) => !value) lets the toggle function have an empty dependency list.
Decision flow
When the linter reports a dependency, ask these questions in order.
The last branch matters. Some values are read inside an effect but should not restart it. A logging callback that fires when a connection opens is one example. Adding it to the array would reconnect on every change. A ref solves that case, and a later chapter covers it.
Common errors
- Omitting a dependency to "run once." The code runs once, but with stale values. If you want setup once, remove the reactive reads instead.
- Adding a dependency to "make it update." If the effect does not read the value, listing it only causes needless restarts. Compute derived data during render.
- Putting
ref.currentin the array. Mutating a ref does not cause a render, so React will not see the change. Refs themselves are stable and need not be listed. - Using an effect to derive state. If you copy props into state in an effect, you get an extra render and a flicker. Compute the value during render, with
useMemoif it is expensive. - Ignoring double runs in development. In Strict Mode, React mounts, unmounts, and remounts each component once to test your cleanup. An effect that breaks under this has a missing cleanup, not a dependency problem.
A practical check
To test whether your array is honest, ask two questions. First, if I read every value the effect uses, is each one in the list? Second, if one of them changed, would I want the effect to tear down and set up again? If the answer to the second question is no for a value the effect needs, the design is wrong. Fix the design with a ref or an updater function, not by deleting the entry.
Exercise
This hook adds a keydown listener. A caller reports that the listener always calls the first onKey function they passed, even after it changes. Why does this happen, and how would you fix it without a ref?
useEffect(() => {
const listener = (e) => onKey(e);
window.addEventListener('keydown', listener);
return () => window.removeEventListener('keydown', listener);
}, []);
Show answer
The effect reads onKey, which is a reactive value, but the empty array claims it reads nothing. The closure keeps the onKey from the first render. Add onKey to the array: [onKey]. The listener is then removed and re-added whenever onKey changes. To avoid restarts on every render, the caller can wrap the handler in useCallback, or the hook can read the latest handler through a ref, which a later chapter covers.
Exercise
A hook has useEffect(() => { setTotal(total + price); }, [price, total]); and it loops forever. Which dependency causes the loop, and what is the fix?
Show answer
total is both read and written. Each run sets a new total, which changes the dependency and runs the effect again. Use an updater, setTotal((t) => t + price), and remove total from the array. If total should be derived from other values, compute it during render instead of in an effect.