The useEffect Infinite Loop & How to Fix It
In this developer note, we break down the useEffect infinite loop — the single most common hooks bug new (and not-so-new) React developers run into — trace exactly why it happens, and walk through the fix along with the habits that keep it from coming back.
The Problem & Root Cause Analysis
The tab freezes. The fan spins up. React DevTools shows the same component rendering hundreds of times a second. Eventually the console fills with a warning every React developer eventually meets face to face:
The Symptom
A component re-renders continuously with no user interaction. CPU usage spikes, the UI becomes unresponsive, and React eventually throws a "Maximum update depth exceeded" warning before the tab locks up entirely.
The Root Cause
A useEffect calls setState unconditionally, and one of its dependencies — usually an object, array, or function — gets a brand-new reference on every render, so the effect re-fires forever.
Before vs. After: The Code Fix
Here's the exact pattern that causes it — an options object recreated on every render, handed straight to useEffect's dependency array — next to the fix:
// ❌ Flawed: a new object every render
function SearchResults({ query }) {
const [results, setResults] = useState([]);
// New object reference on every single render!
const options = { query, limit: 20 };
useEffect(() => {
fetchResults(options).then(setResults);
}, [options]); // 🔁 "options" is never === last time
return <ResultsList items={results} />;
}
// ✅ Fixed: depend on primitives, not objects
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
const options = { query, limit: 20 };
fetchResults(options).then(setResults);
}, [query]); // ✅ "query" is a primitive string
return <ResultsList items={results} />;
}
Complete Implementation: A Reusable Debounced Fetch Hook
Moving the object inside the effect fixes this one case, but the sturdier long-term fix is pulling the pattern into a custom hook so the dependency rules only have to be gotten right once:
import { useState, useEffect } from 'react';
// Reusable hook: debounces a value and fetches on change.
// Depends only on primitives (query, delayMs) — never an
// object or function recreated on every render.
export function useDebouncedFetch(query, delayMs = 300) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!query) {
setData([]);
return;
}
setLoading(true);
const timer = setTimeout(() => {
fetchResults({ query, limit: 20 })
.then(setData)
.finally(() => setLoading(false));
}, delayMs);
// Cleanup: cancel the pending fetch if query changes again
return () => clearTimeout(timer);
}, [query, delayMs]);
return { data, loading };
}
import { useState } from 'react';
import { useDebouncedFetch } from './useDebouncedFetch';
function SearchResults() {
const [query, setQuery] = useState('');
const { data, loading } = useDebouncedFetch(query);
return (
<>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
{loading ? <Spinner /> : <ResultsList items={data} />}
</>
);
}
{
"extends": ["react-app"],
"plugins": ["react-hooks"],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}
Step-by-Step Debugging Workflow
When a component won't stop rendering, work through these steps in order rather than guessing at the fix:
Step 1: Confirm It's useEffect
Open React DevTools' Profiler and record a render. If one component re-renders dozens of times with no prop changes, the cause is almost always a setState call inside an effect.
Step 2: Read the Dependency Array Literally
For every value in the array, ask: "does this get a new reference every render?" Objects, arrays, and inline functions almost always do unless they're memoized.
Step 3: Depend on Primitives, Not Objects
Move object/array construction inside the effect, or destructure the primitive fields you actually need and list those instead.
Step 4: Turn On exhaustive-deps
Enable the react-hooks/exhaustive-deps ESLint rule so the compiler — not production users — catches the next one.
Common useEffect Pitfalls & How to Spot Them
The object-dependency loop above is the most common version, but it's not the only one. These show up just as often:
Missing Dependency Array Entirely
A useEffect with no second argument runs after every render. If it also calls setState, that's an unconditional infinite loop by itself.
Inline Functions Passed as Props
An inline onClick={() => doThing()} passed to a memoized child defeats React.memo — wrap it in useCallback if it's also a dependency somewhere downstream.
Prefer Functional setState Updates
setCount(c => c + 1) doesn't need count in the dependency array at all — often the simplest way to shrink a dependency list is to not need the value in the first place.
Terminal Cheatsheet & Diagnostic Commands
Handy one-liners for catching this class of bug before it ships:
Render Flow & Profiling Visuals
Developer Pro-Tip
If you find yourself reaching for useMemo or useCallback just to stabilize a dependency, first ask whether that value needs to be a dependency at all. Removing the need is almost always simpler than memoizing around it.
Source Code, Docs & Discussion
GitHub Profile
See more hooks patterns and project source on GitHub.
Official React Docs
The official reference on useEffect, dependency arrays, and the rules of hooks.
Developer Discussions
Hit a useEffect bug that doesn't fit this pattern? Get in touch.
Stable Dependencies, Stable Components
The useEffect infinite loop isn't really a React bug — it's a reference-equality bug wearing a React costume. Depend on primitives, memoize deliberately instead of defensively, and let ESLint catch the rest.
Comments
Post a Comment