Sub topic 11
Objects and Functions as Dependencies
This chapter assumes you know useState, closures, and how the dependency array decides when an effect re-runs. You should also be comfortable with the idea that every render creates a fresh set of local variables.
Why objects and functions cause trouble
React compares each dependency with the value from the previous render using Object.is. For numbers, strings and booleans, this works as you expect: 3 is the same as 3.
Objects, arrays and functions are compared by reference, not by contents. Two objects with identical fields are different values if they were created separately.
const a = { room: 'general' };
const b = { room: 'general' };
console.log(Object.is(a, b)); // false
console.log(Object.is(a, a)); // trueA component function runs again on every render. Any object, array or function created in its body is a new value each time. If that value is in a dependency array, React sees a change on every render and re-runs the effect, even though nothing meaningful changed.
The symptom: an effect that runs too often
Here is a chat connection that reconnects on every render.
import { useEffect, useState } from 'react';
function createConnection({ serverUrl, roomId }) {
return {
connect() { console.log(`Connecting to ${roomId} at ${serverUrl}`); },
disconnect() { console.log(`Disconnected from ${roomId}`); },
};
}
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const options = { serverUrl: 'https://localhost:1234', roomId };
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]);
return (
<input value={message} onChange={(e) => setMessage(e.target.value)} />
);
}Each keystroke updates message and re-renders the component. That creates a new options object, the dependency changes, and the effect disconnects and reconnects. The console fills with connect and disconnect lines for every character typed.
If the effect also calls setState with a new object, the loop never stops. That gives you an infinite render loop, which is the other common form of this bug.
Fix 1: depend on primitives
The most direct fix is to depend on the primitive values the effect actually reads.
import { useEffect, useState } from 'react';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
const options = { serverUrl: 'https://localhost:1234', roomId };
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return (
<input value={message} onChange={(e) => setMessage(e.target.value)} />
);
}Creating options inside the effect removes it from the dependency list. The effect now depends only on roomId, a string, so typing no longer triggers a reconnect. If the effect needs serverUrl from props, list serverUrl too. Destructure object props into their fields before listing them.
Fix 2: move constants out of the component
If an object or function does not use props or state, it does not need to live inside the component. A value defined at module level is created once, so its reference never changes and it is not a reactive value.
const options = { serverUrl: 'https://localhost:1234', roomId: 'general' };
function ChatRoom() {
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, []);
return <p>Connected</p>;
}The linter knows that module-level values cannot change between renders, so it does not ask you to list them.
Fix 3: move functions into the effect
A function declared in the component body is recreated on every render. If an effect calls it, the linter requires it as a dependency, and the effect re-runs each time.
import { useEffect, useState } from 'react';
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
const controller = new AbortController();
async function load() {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
setResults(await res.json());
}
load().catch((err) => {
if (err.name !== 'AbortError') console.error(err);
});
return () => controller.abort();
}, [query]);
return <ul>{results.map((r) => <li key={r.id}>{r.title}</li>)}</ul>;
}Because load is only used by this effect, it belongs inside it. The effect then depends on query, which is what actually matters.
Fix 4: stabilize with useMemo and useCallback
Sometimes the object or function must be created in the component, for example because the component passes it to a child or a custom hook. You can keep its identity stable between renders with useMemo (for values) and useCallback (for functions). Both take their own dependency array and return the previous value when those dependencies are unchanged.
import { useCallback, useEffect, useMemo, useState } from 'react';
function Feed({ category, onLoaded }) {
const [items, setItems] = useState([]);
const params = useMemo(
() => ({ category, limit: 20 }),
[category]
);
const load = useCallback(async () => {
const qs = new URLSearchParams(params).toString();
const res = await fetch(`/api/items?${qs}`);
const data = await res.json();
setItems(data);
onLoaded?.(data.length);
}, [params, onLoaded]);
useEffect(() => {
load();
}, [load]);
return <p>{items.length} items</p>;
}This works only if every input is stable. Here onLoaded comes from the parent. If the parent passes an inline arrow function, onLoaded changes on every parent render, load changes with it, and the effect re-runs anyway.
Prefer fixes 1 to 3 when they apply. Memoization adds code, and the chain of dependencies is easy to break by accident.
Fix 5: stop depending on the value at all
Sometimes an effect needs a function only to react to an event, not to re-synchronize. The common case is a callback prop like onMessage. You do not want to reconnect whenever the parent passes a new function.
Two options exist. For state updates, the functional form of setState removes the need to read the current state.
useEffect(() => {
const id = setInterval(() => {
setItems((prev) => [...prev, Date.now()]);
}, 1000);
return () => clearInterval(id);
}, []);For callbacks from props, you can keep the latest version in a ref and read it inside the effect. A later chapter covers this pattern and React's dedicated tools for it. For now, note that suppressing the lint rule is not a safe shortcut here, because it hides stale values.
Choosing a fix
| Situation | Best fix |
|---|---|
| Object built from props or state, used only in the effect | Create it inside the effect, depend on its primitives |
| Object or function with no reactive inputs | Move it outside the component |
| Helper function used only by the effect | Declare it inside the effect |
| Value or function shared with render or children | `useMemo` or `useCallback` |
| Callback prop that should not cause re-synchronization | Ref pattern (see the later chapter) |
| Next state depends on previous state | Functional `setState` |
Edge cases and gotchas
- Arrays behave like objects.
[a, b]is a new array each render. Depend on the items or on a joined primitive such asids.join(','). - Props can be unstable too. A parent that passes
style={{ color: 'red' }}oronChange={() => ...}creates new references each render. The child cannot fix this by itself, except by avoiding that prop as a dependency. - Deep comparison is not built in. Do not use
JSON.stringify(obj)as a dependency as a habit. It is slow for large data and breaks on functions,undefinedand circular references. - Mutation hides changes. If you mutate an object in place and keep the same reference, React sees no change and the effect does not re-run. Always create a new object when updating state.
- Do not silence the linter.
// eslint-disable-next-line react-hooks/exhaustive-depstrades an obvious extra run for a hidden stale-value bug. Fix the dependency instead.
Checking your work
To find an unstable dependency, log the values and compare them across renders.
import { useEffect, useRef } from 'react';
function useWhyChanged(name, value) {
const prev = useRef(value);
useEffect(() => {
if (!Object.is(prev.current, value)) {
console.log(`${name} changed`, prev.current, value);
}
prev.current = value;
});
}Call useWhyChanged('options', options) in the component. If it logs on every render and the printed objects look identical, the reference is unstable.
Exercise
A component defines const filters = { status, page }; in its body and runs useEffect(() => { fetchItems(filters); }, [filters]);. The effect fires on every render, even when status and page have not changed. Explain why, and show two ways to fix it.
Show answer
filters is a new object on every render, and React compares dependencies by reference with Object.is, so the dependency always looks changed. Fix 1: create the object inside the effect and depend on primitives: useEffect(() => { fetchItems({ status, page }); }, [status, page]);. Fix 2: keep the object outside the effect but memoize it: const filters = useMemo(() => ({ status, page }), [status, page]); and keep [filters] as the dependency. The first is simpler when the object is used only in the effect.
Exercise
You wrap a function in useCallback(() => save(draft), [draft, onSaved]), and an effect depends on it. The effect still re-runs on every parent render. What is the most likely cause?
Show answer
onSaved is a prop, and the parent probably passes a new inline function each render. That changes the useCallback dependency, so the callback is recreated and the effect re-runs. Either memoize the function in the parent, or avoid depending on it in the child, for example by reading the latest version through a ref.