Sub topic 7
Getting dependency arrays right
This chapter assumes you know useState and useEffect basics, closures, and the Rules of Hooks. It covers how the dependency array decides when an effect re-runs, and the errors that come from getting it wrong.
What the array means
The dependency array lists every reactive value the effect reads. A reactive value is a prop, a piece of state, or anything declared inside the component or hook body. After each render, React compares each listed value to its value from the previous render using Object.is. If any value differs, React runs the cleanup from the last run and then runs the effect again.
The array is not a list of values you want to trigger the effect. It is a description of what the effect uses. If the effect reads it, list it.
| Array | When the effect runs |
|---|---|
| Omitted | After every render |
| `[]` | Once after mount, cleanup on unmount |
| `[a, b]` | After mount, then whenever `a` or `b` changes |
A correct example
useDebouncedValue reads two reactive values, value and delay. Both are listed.
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;
}When value changes, React clears the old timer through the cleanup and starts a new one. setDebounced is not listed because React guarantees that state setter functions are stable.
Stale closures
An effect captures the values from the render in which it was created. If you leave a value out of the array, the effect keeps using the old copy.
Suppose the array in the example above were []. The timer would always be created with the first value and the first delay. Later changes would be ignored, and the hook would return the initial value forever. This is a stale closure.
Objects, arrays and functions
Object.is compares objects by identity, not by content. A new object or function is created on every render, so a dependency like { page: 1 } looks changed every time.
// Re-runs on every render because `options` is a new object each time
function useSearch(query) {
const options = { query, limit: 10 };
useEffect(() => {
runSearch(options);
}, [options]);
}You have three ways to fix this, in order of preference:
- Depend on primitives. Move the object creation inside the effect and list
queryinstead. - Move constant objects outside the component, where they are created once.
- Memoize the value with
useMemooruseCallbackwhen it must be created during render.
import { useEffect } from 'react';
export function useSearch(query) {
useEffect(() => {
const options = { query, limit: 10 };
runSearch(options);
}, [query]);
}Choosing between dependencies and other tools
If an effect needs a value but should not re-run when it changes, adding it to the array is wrong and removing it is also wrong. Consider these alternatives:
- Use a functional state update, such as
setOn((value) => !value), so the effect does not need to read the current state. - Read the latest value through a ref, as
useEventListenerdoes. A later chapter covers this pattern. - Move the logic out of the effect if it responds to a user action and not to rendering.
Common errors
- Omitting the array by accident, so the effect runs after every render and may cause a render loop when it sets state.
- Listing an object or function created in the render body, which re-runs the effect every time.
- Passing an inline callback from the caller into your hook and listing it, which forces callers to memoize.
- Disabling the lint rule, which hides stale closures.
Exercise
A hook has useEffect(() => { const id = setInterval(() => setCount(count + 1), 1000); return () => clearInterval(id); }, []);. The counter stops at 1. Why, and how do you fix it without adding count to the array?
Show answer
The effect runs once, so its closure keeps the count from the first render, which is 0. Every tick sets the count to 1. Use a functional update, setCount((c) => c + 1). The effect then does not read count, so the empty array is correct.