Error: Maximum update depth exceeded
Quick answer
A state update is triggering a re-render that triggers the same update again, looping forever. The most common cause is calling `setState` directly in the render body, or inside a `useEffect` with a dependency array that changes every render.
What causes this error
React detects when a component re-renders itself in a tight loop and stops it before it freezes the browser tab. This almost always traces back to a state setter being called somewhere that runs on every single render, rather than only in response to a specific event.
The Fix
// Wrong — runs on every render, sets state, triggers another render, forever
function Component() {
const [count, setCount] = useState(0);
setCount(count + 1); // in the render body — infinite loop
return <div>{count}</div>;
}
// Wrong — object/array literal as a dependency changes identity every render
useEffect(() => {
setData({ value: 1 });
}, [{ value: 1 }]); // new object every render, effect never stabilizes
// Fix — only update state in response to an actual event or a stable dependency
useEffect(() => {
setData({ value: 1 });
}, []); // empty array = runs onceCommon causes / variations
- Calling a state setter directly in the component body instead of inside an event handler or effect
- An object or array literal in a
useEffectdependency array, which is a new reference every render - Two components each updating state in response to the other's change, bouncing back and forth
Related errors
See also: Hydration failed because the server rendered HTML didn't match the client.
Was this fix helpful?
Comments
Loading comments...