Sub topic 14
Linting and Debugging Effects
This chapter assumes you can write useEffect with dependencies and cleanup. It also assumes you know how stale closures and unstable dependencies arise, and that you have an ESLint setup in your project. Here you will use the Hooks lint rules as a diagnostic tool, then learn how to find out why an effect ran when it should not have, or did not run when it should have.
What the Hooks lint rules check
The package eslint-plugin-react-hooks ships two rules.
react-hooks/rules-of-hooksreports hooks called conditionally, inside loops, or outside components and custom hooks. Treat violations as errors.react-hooks/exhaustive-depscompares the dependency array with the reactive values (props, state, and anything derived from them during render) that the effect callback reads. It warns when the two lists differ.
A minimal flat config looks like this:
import reactHooks from 'eslint-plugin-react-hooks';
export default [
{
files: ['**/*.{js,jsx}'],
languageOptions: {
parserOptions: { ecmaFeatures: { jsx: true } },
},
plugins: { 'react-hooks': reactHooks },
rules: {
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
},
},
];The rule works by static analysis of the source text. It does not run your code, so it cannot know that a value is stable at runtime unless the pattern is recognizable. It knows that the setter returned by useState and the ref object from useRef are stable. It does not know that a function you received as a prop is stable.
Reading the warnings
Each message points to a specific mismatch. This table maps the common ones to the usual fix.
| Warning | What it means | Usual fix |
|---|---|---|
| Missing dependency: `query` | The effect reads `query`, but the array omits it. The effect may use a stale value. | Add `query` to the array. |
| Unnecessary dependency: `window.innerWidth` | The array contains a value that is not reactive. | Remove it. |
| The `options` object makes the dependencies change on every render | An object or function is created in the component body. | Move it inside the effect, move it outside the component, or depend on its primitive fields. |
| The `fetchData` function makes the dependencies change on every render | A function defined in the body is used by the effect. | Define the function inside the effect. |
| Effect callback must not be async | You wrote `useEffect(async () => ...)`. | Define an async function inside and call it. |
Fix the cause, not the warning
The lint rule is almost always pointing at a real bug. Suppose you write this:
useEffect(() => {
fetch(`/api/search?q=${query}`).then((res) => res.json()).then(setResults);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);The effect runs once with the first query and never again. Typing in the search box changes nothing. Removing the suppression shows the warning is correct. The fix adds the dependency and, as you learned in the data fetching chapter, a cleanup to avoid race conditions:
import { useEffect, useState } from 'react';
function Search({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
})
.then((res) => res.json())
.then(setResults)
.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>
);
}Debugging an effect that runs too often
When the lint rule is clean but an effect still runs more than expected, first find out which dependency changed. React compares dependencies with Object.is, so a new object or array each render counts as a change, even if its contents are equal.
The following helper hook logs which entries changed between renders. It has no dependency array on purpose, so it runs after every render. Use it only while debugging and delete it afterward.
import { useEffect, useRef } from 'react';
function useChangedDeps(label, deps) {
const previous = useRef(deps);
useEffect(() => {
const changes = deps
.map((value, index) => ({
index,
from: previous.current[index],
to: value,
}))
.filter(({ from, to }) => !Object.is(from, to));
if (changes.length > 0) {
console.log(`[${label}] dependencies changed:`, changes);
}
previous.current = deps;
});
}Call it with the same array you pass to the effect under investigation, for example useChangedDeps('Profile', [options, id]). If the log shows a changed options entry whose from and to print identically, you have found an unstable object.
A typical infinite loop
An effect that sets state, combined with an unstable dependency, produces a loop:
import { useEffect, useState } from 'react';
function Profile({ id }) {
const [data, setData] = useState(null);
const options = { id }; // new object on every render
useEffect(() => {
fetch(`/api/profile/${options.id}`)
.then((res) => res.json())
.then(setData);
}, [options]);
return <p>{data ? data.name : 'Loading...'}</p>;
}The sequence is: render, effect runs, setData triggers a render, options is a new object, the effect runs again. The Network tab shows the same request repeating. Depend on the primitive instead:
useEffect(() => {
fetch(`/api/profile/${id}`)
.then((res) => res.json())
.then(setData);
}, [id]);A debugging workflow
The diagram shows the order in which to check things.
Tools beyond console logging
- React DevTools, Components tab. Enable "Highlight updates when components render" in the settings to see which components re-render. A component that flashes continuously is likely stuck in a loop.
- React DevTools, Profiler tab. Enable "Record why each component rendered while profiling" in the Profiler settings. After recording, select a commit and read the reason, such as "Hooks changed" or "Props changed".
- Browser Network tab. Duplicate requests with the same URL point to a repeating effect. Requests marked as canceled usually mean your abort cleanup works.
- Browser debugger. Put a
debuggerstatement or a breakpoint at the top of the effect and inspect the call stack. Hovering over the variables in a stale closure shows the old values the effect captured. - Labeled logs in setup and cleanup. Log
setupandcleanupwith the dependency values. The expected order is always setup, then cleanup with the old values, then setup with the new values.
Strict Mode as a free test
In development, Strict Mode runs each effect's setup, cleanup, and setup again on mount. Treat this as a test of your cleanup. If you see duplicate subscriptions, two timers, or two uncancelled requests after the extra cycle, the cleanup does not fully undo the setup. Do not remove Strict Mode to hide the symptom. Fix the cleanup instead.
Common mistakes
- Adding
eslint-disablebefore understanding the warning. - Putting a ref's
.currentvalue in the dependency array. Mutating it does not trigger a render, so the effect will not re-run. - Fixing a loop by deleting the dependency array. This makes the effect run after every render and usually makes the loop worse.
- Wrapping everything in
useCallbackanduseMemoto satisfy the linter, when moving the function inside the effect is simpler. - Reading a log from the render body and assuming it reflects the effect. Log inside the effect to see the values it actually captured.
Exercise
A component contains const filters = { category, page }; and an effect useEffect(() => { loadItems(filters).then(setItems); }, [filters]);. The lint rule is silent, but the Network tab shows loadItems requests firing without stopping. Explain why, and show a fix.
Show answer
filters is a new object on every render, so Object.is reports a change each time. The effect runs, setItems triggers a render, a new filters object is created, and the effect runs again. Fix it by depending on the primitive values and building the object inside the effect: useEffect(() => { loadItems({ category, page }).then(setItems); }, [category, page]);.
Exercise
A teammate fixes a missing-dependency warning on userId by adding // eslint-disable-next-line react-hooks/exhaustive-deps above }, []);. What bug can this cause, and what is the correct change?
Show answer
The effect captures userId from the first render and never re-runs, so after userId changes the component keeps showing data for the old user. The correct change is to remove the suppression and use [userId] as the dependency array, ideally with a cleanup such as an AbortController so an older response cannot overwrite a newer one.