Sub topic 4
Dependencies: controlling when an effect re-runs
This chapter assumes you know function components, useState, closures, and how a state change causes a re-render. It also assumes you have seen a basic useEffect call. Here you learn how the dependency array decides when an effect runs again, and which mistakes come up most often.
What the dependency array does
useEffect takes two arguments: a function (the effect) and an optional array of dependencies. After every render, React compares each value in the array with the value from the previous render. If every value is the same, React skips the effect. If at least one value differs, React runs the effect again after that render is committed to the screen.
The comparison uses Object.is. For numbers, strings and booleans, this means "same value". For objects, arrays and functions, it means "same reference", not "same contents".
There are three forms:
| Form | When the effect runs |
|---|---|
| `useEffect(fn)` | After every render |
| `useEffect(fn, [])` | After the first render only (and cleanup on unmount) |
| `useEffect(fn, [a, b])` | After the first render, then after any render where `a` or `b` changed |
import { useEffect, useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}The effect reads count, so count is listed. When the user clicks, count changes, the component re-renders, React sees 1 !== 0, and the effect updates the title. A re-render caused by something else, such as a parent passing new props that Counter ignores, leaves count unchanged, so the effect is skipped.
Dependencies describe what the effect reads
The array is not a trigger list that you choose freely. It is a declaration of which reactive values the effect function uses. A reactive value is anything that can change between renders: props, state, and any variable or function declared inside the component body.
The rule is simple: every reactive value the effect reads must appear in the array. Values that live outside the component (module-level constants, imports) and setState functions from useState never change, so they do not need to be listed.
The mental model is synchronization. The effect says "make the outside world match these values". When the values change, the effect runs again to re-synchronize. You do not decide when to re-run. The data decides.
Note the order in the "run" branch: before running an effect again, React runs the cleanup from the previous run. The next chapter covers cleanup in detail. For now, remember that a re-run is always "cleanup, then effect".
Common mistakes with the array
Omitting the array by accident
Without an array, the effect runs after every render. If the effect also sets state, you get a loop.
import { useEffect, useState } from 'react';
function Broken() {
const [count, setCount] = useState(0);
// Runs after every render, and each run triggers another render.
useEffect(() => {
setCount(count + 1);
});
return <p>{count}</p>;
}Each render runs the effect, the effect sets state, the state change causes a render, and so on. React does not stop this until the browser tab struggles. Adding [] here would stop the loop, but it would also hide the real question: why is this effect needed at all?
Lying about dependencies
Leaving out a value the effect reads makes the effect use the value from the render when it last ran, which may be out of date.
import { useEffect, useState } from 'react';
function Search({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((res) => res.json())
.then(setResults);
}, []); // Bug: query is read but not listed
return <p>{results.length} results for {query}</p>;
}The effect runs once with the first query. When the prop changes, the heading updates but the results never do. The fix is to list query:
useEffect(() => {
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((res) => res.json())
.then(setResults);
}, [query]);The problem is a stale closure, which a later chapter treats in depth. The short version: each render creates a new effect function that closes over that render's values. If React skips the effect, the old function, with the old values, stays in charge.
Treating `[]` as "run once"
[] means "this effect reads no reactive values". It is correct for work that truly depends on nothing, such as subscribing to a window event. It is wrong when used as a shortcut for "only fetch on mount" while the effect uses props or state. In development, React Strict Mode also runs mount effects twice, so even a correct [] effect must tolerate a second run. A later chapter explains why.
Objects and functions as dependencies
Because comparison is by reference, an object or function created during rendering is a new value on every render.
import { useEffect } from 'react';
function Chat({ roomId }) {
const options = { roomId, secure: true }; // new object each render
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // changes on every render
}Here options is "different" every time, so the effect disconnects and reconnects after every render. The values inside have not changed, but the reference has. There are three common fixes, in order of preference:
- Create the object inside the effect and depend on the primitives it uses.
- Depend on the primitive values directly, such as
roomId. - Memoize the object with
useMemo(or a function withuseCallback) when it must be created outside the effect.
useEffect(() => {
const connection = createConnection({ roomId, secure: true });
connection.connect();
return () => connection.disconnect();
}, [roomId]);Now the effect depends only on a string. It re-runs exactly when the room changes.
Updating state from an effect without depending on it
Sometimes an effect needs to change state based on the previous value, but you do not want that state in the array. Use the functional update form. The updater receives the latest value, so the effect does not need to read seconds itself.
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds} seconds elapsed</p>;
}Because the effect never reads seconds directly, [] is honest, and the interval is created once. If you wrote setSeconds(seconds + 1) instead, the effect would read seconds, you would have to list it, and the interval would be torn down and recreated every second.
Edge cases
NaNand-0:Object.is(NaN, NaN)istrue, so aNaNdependency does not cause endless re-runs.Object.is(0, -0)isfalse, which rarely matters.- Mutated objects: If you mutate an object or array in place and keep the same reference, React sees no change and skips the effect. Always create a new object or array when updating state.
- Changing array length: The number of dependencies must stay the same between renders. React warns if it changes, usually because of a conditional or a spread.
- Refs:
ref.currentis not reactive. Changing it does not cause a render, and listingref.currentin the array does not reliably trigger an effect. - Derived values: If a value can be computed from props or state during render, depend on the source values, or compute it in the render body and avoid the effect.
A checklist for writing the array
- Write the effect body first.
- List every prop, state value and component-scoped variable it reads.
- If the list causes unwanted re-runs, change the code: move values inside the effect, use a functional update, or memoize.
- Use the
react-hooks/exhaustive-depslint rule. It reports missing dependencies and is right far more often than your intuition.
Exercise
This component should reload comments when postId changes, but it only loads them once. Why, and what is the fix?
function Comments({ postId }) {
const [comments, setComments] = useState([]);
useEffect(() => {
fetch(/api/posts/${postId}/comments)
.then((res) => res.json())
.then(setComments);
}, []);
return <p>{comments.length} comments</p>;
}
Show answer
The effect reads postId, which is a prop and therefore a reactive value, but the dependency array is empty. React skips the effect after the first render, so it keeps using the first postId. Change the array to [postId] so the effect re-runs whenever the post changes. A cleanup that aborts the previous request would also protect against a slow earlier response arriving late.
Exercise
A component creates const filters = { tag, sort }; in its body and lists [filters] in an effect's dependency array. The effect runs after every render. Why, and how would you fix it?
Show answer
filters is a new object on every render, and React compares dependencies by reference with Object.is, so it always looks changed. Fix it by listing the primitives [tag, sort] and building the object inside the effect, or by wrapping the object in useMemo with [tag, sort] as its dependencies.