Sub topic 11
Objects and functions as dependencies
This chapter assumes you know useState, the basic useEffect syntax, how the dependency array decides when an effect runs, and how JavaScript closures work.
Why objects and functions cause trouble
React compares each dependency with the previous render's value using Object.is. For strings, numbers and booleans, equal values compare as equal. Objects, arrays and functions compare by identity, so two objects with the same contents are different values.
A component function runs again on every render. Any object or function written in its body is created anew each time. If that value is a dependency, the effect re-runs after every render, even though nothing meaningful changed.
An effect that loops forever
import { useEffect, useState } from 'react';
function Results({ query, page }) {
const [results, setResults] = useState([]);
const params = { q: query, page }; // new object on every render
useEffect(() => {
fetch(`/api/search?${new URLSearchParams(params)}`)
.then((res) => res.json())
.then(setResults); // new array, so another render
}, [params]);
return <p>{results.length} results</p>;
}The sequence is: render, effect, setResults, render, a new params object, effect again. The component fetches in a loop.
Fix 1: depend on primitives
Build the object inside the effect and list the primitive values it uses. Add the cleanup from the data-fetching chapter while you are there.
import { useEffect, useState } from 'react';
function Results({ query, page }) {
const [results, setResults] = useState([]);
useEffect(() => {
const controller = new AbortController();
const params = new URLSearchParams({ q: query, page });
fetch(`/api/search?${params}`, { signal: controller.signal })
.then((res) => res.json())
.then(setResults)
.catch((err) => {
if (err.name !== 'AbortError') console.error(err);
});
return () => controller.abort();
}, [query, page]);
return <p>{results.length} results</p>;
}The effect now re-runs only when query or page changes.
Fix 2: move values out of the component
If an object or function uses no props or state, define it at module level. It is created once, so it never changes between renders and does not belong in the dependency array.
const DEFAULT_OPTIONS = { credentials: 'include' };
function loadUser(id, signal) {
return fetch(`/api/users/${id}`, { ...DEFAULT_OPTIONS, signal });
}Fix 3: define functions inside the effect
If only the effect calls a function, declare it inside the effect. Then the function is no longer a dependency. Only the values it reads are.
Fix 4: memoize as a last resort
Sometimes a parent must pass an object or function to a child that uses it in an effect. In that case, keep its identity stable with useMemo or useCallback.
import { useCallback, useMemo } from 'react';
function Parent({ userId }) {
const filters = useMemo(() => ({ userId, active: true }), [userId]);
const onDone = useCallback(() => console.log('done', userId), [userId]);
return <Child filters={filters} onDone={onDone} />;
}filters and onDone keep the same identity until userId changes. The child's effect can then list them without re-running on every render.
Choosing a fix
| Situation | Preferred fix |
|---|---|
| Object built from props or state, used only in the effect | Build it inside the effect and depend on the primitives |
| Constant object or helper function | Move it outside the component |
| Function called only by the effect | Declare it inside the effect |
| Value passed down from a parent | `useMemo` or `useCallback` in the parent |
Exercise
A component has const options = { sort, limit }; in its body, and an effect lists [options] as its dependency. The effect calls setData with a freshly fetched array. Why does it loop, and what is the simplest fix?
Show answer
options is a new object on every render, so Object.is reports a change each time. The effect runs, setData triggers a render, a new options is created, and the effect runs again. The simplest fix is to build the object inside the effect and use [sort, limit] as the dependencies.