0
0
ReactDebug / FixBeginner · 4 min read

How to Fix Maximum Update Depth Exceeded Error in React

The Maximum update depth exceeded error in React happens when a component keeps updating itself endlessly, usually due to calling setState or updating state inside the render or an effect without proper conditions. To fix it, ensure state updates happen only when necessary, often by adding dependency arrays in useEffect or avoiding state changes directly in the render phase.
🔍

Why This Happens

This error occurs because React detects an infinite loop of updates. For example, if you update state inside the component's body or inside a useEffect without limiting when it runs, React keeps re-rendering the component endlessly.

jsx
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  // This causes infinite updates because setCount runs every render
  setCount(count + 1);

  return <div>Count: {count}</div>;
}

export default Counter;
Output
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside render.
🔧

The Fix

Move state updates out of the render phase. Use useEffect with a proper dependency array to update state only when needed. This stops the infinite loop by controlling when updates happen.

jsx
import React, { useState, useEffect } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (count < 5) {
      setCount(count + 1);
    }
  }, [count]);

  return <div>Count: {count}</div>;
}

export default Counter;
Output
Count: 5
🛡️

Prevention

To avoid this error in the future:

  • Never call setState directly inside the component body (render phase).
  • Use useEffect with dependency arrays to control when side effects run.
  • Check conditions before updating state inside effects to prevent loops.
  • Use linting tools like eslint-plugin-react-hooks to catch missing dependencies or misuse of hooks.
⚠️

Related Errors

Similar errors include:

  • Too many re-renders: Happens when state updates cause immediate re-render without stopping conditions.
  • React Hook useEffect has missing dependencies: Can cause unexpected repeated effects.

Fixes usually involve adding proper dependency arrays and conditional logic.

Key Takeaways

Never update state directly inside the render function to avoid infinite loops.
Use useEffect with dependency arrays to control when state updates happen.
Always add conditions before calling setState inside effects to prevent repeated updates.
Lint your code with react-hooks rules to catch common hook mistakes early.