Sub topic 14
Linting and debugging effects
This chapter assumes you know useEffect, dependency arrays, cleanup functions, and the difference between stale closures and unstable dependencies from earlier chapters. It shows how to let tooling catch effect bugs and how to find the ones it misses.
Let the linter check your dependencies
The eslint-plugin-react-hooks package ships two rules. rules-of-hooks reports hooks called inside conditions or loops. exhaustive-deps compares the reactive values an effect reads (props, state, and anything derived from them) with its dependency array.
import reactHooks from 'eslint-plugin-react-hooks';
export default [
{
plugins: { 'react-hooks': reactHooks },
rules: {
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
},
},
];Consider this effect:
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);
}, []); // warning: missing dependency 'query'
return <p>{results.length} results</p>;
}The linter is right. With [], the effect runs once and never sees a new query. Fix the code instead of silencing the rule. The usual fixes are:
- Add the value to the array, here
[query]. - Move the value or function inside the effect if only that effect uses it.
- Use a functional update (
setCount((c) => c + 1)) so the effect does not read the state. - Wrap a function in
useCallback, or move it outside the component, when it must stay a dependency.
Debug what the linter cannot see
The linter checks which values you listed. It cannot tell you why an effect ran at an unexpected time. This small hook logs which dependency changed between renders:
import { useEffect, useRef } from 'react';
function useChangedDeps(label, deps) {
const previous = useRef(deps);
useEffect(() => {
deps.forEach((dep, i) => {
if (!Object.is(dep, previous.current[i])) {
console.log(label, `dependency ${i} changed`, previous.current[i], '->', dep);
}
});
previous.current = deps;
});
}Call useChangedDeps('Search', [query, options]) next to the effect you suspect. If the log shows an object changing on every render, you have an unstable dependency. Also log inside both the effect body and its cleanup. In development, Strict Mode runs setup, cleanup, then setup again on mount. If the second run breaks something, the cleanup is incomplete.
Match the symptom to the cause
| Symptom | Likely cause | First check |
|---|---|---|
| Infinite render loop | Effect sets state that is also a dependency | Does the effect update a value it lists? |
| Effect runs on every render | New object or function in dependencies | Run `useChangedDeps` |
| Old value inside a callback | Stale closure, missing dependency | Read the `exhaustive-deps` warning |
| Duplicate listeners or requests | Cleanup missing | Compare setup and cleanup logs |
| Works in production, breaks in development | Effect is not resilient to remount | Is each setup undone by its cleanup? |
You can also use the Profiler in React DevTools, or the "Highlight updates" option, to see which components re-render.
Exercise
An effect lists [options], where options is an object literal created in the component body. The effect re-runs on every render. Name two ways to fix it without disabling the linter.
Show answer
Move the object outside the component if it is constant, or build it inside the effect so it is not a dependency. You can also memoize it with useMemo, or depend on the primitive values it contains, such as options.page.