Error: Maximum update depth exceeded - 10 Causes and Fixes in React

Error: Maximum update depth exceeded means a React component called setState (or a useState setter) in a way that triggers another render, which triggers another setState, forever. React cuts the cycle off at a fixed depth and throws instead of freezing the tab.

The full message usually continues with: "This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." The hooks-era variant is the same loop with a different entry point - almost always an effect whose dependency changes every render.

This page lists the 10 concrete shapes this loop takes, most common first, each with a reproduction you can paste into a component and a fix that differs by the exact lines that matter. If your case does not match any of them, use the diagnostic checklist to narrow it down. Close-up of a laptop screen displaying code, set against a dark backdrop with blue lighting for a tech-focused ambiance.

ErrorError: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Where it happensReact (JavaScript/TypeScript) - DOM or Native, class components and function components with hooks. Thrown during the render/commit phase, not at build time.
What it meansA state update is causing a render that causes the same state update again, and React stopped counting.

The Fast Fix

Nine times out of ten it is a useEffect that sets state and depends on a value it recreates every render. Pin the dependency to a primitive, or guard the write:

// before: `options` is a new object literal every render -> effect runs every render
useEffect(() => { setData(load(options)); }, [options]);

// after: depend on the primitive that actually changes
useEffect(() => { setData(load({ id })); }, [id]);

If you cannot reduce the dependency, bail out before writing: if (next === data) return; inside the effect. For class components, the equivalent is an if comparing prevProps/prevState at the top of componentDidUpdate.

If neither shape fits, work through the diagnostic checklist below - the stack trace alone rarely names the guilty component.

What Is Actually Causing It

1. useEffect with no dependency array sets state

Reproduce it

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

  useEffect(() => {
    setCount(count + 1); // runs after every render
  });

  return <span>{count}</span>;
}

Why it happens — An effect without a dependency array runs after every commit. Setting state schedules another render, which runs the effect again. The cycle never narrows, so React hits its nested-update limit.

The fix

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

  useEffect(() => {
    setCount(c => c + 1); // runs once
  }, []); // <- empty array: after mount only

  return <span>{count}</span>;
}

Changed: added [] so the effect runs on mount only, and used the updater form so count is not a stale capture.

Confirm it worked — Add console.log('effect') as the first line of the effect. One line in the console after mount means it is fixed; a flood means the dependency array is still missing or wrong.


2. Effect depends on an object or array literal

Reproduce it

function List({ userId }) {
  const [rows, setRows] = useState([]);
  const query = { userId, limit: 20 }; // new object identity each render

  useEffect(() => {
    fetchRows(query).then(setRows);
  }, [query]);

  return <Table rows={rows} />;
}

Why it happens — React compares dependencies with Object.is. { userId, limit: 20 } is a fresh object on every render, so the comparison always fails, the effect reruns, setRows renders again, and the loop closes.

The fix

function List({ userId }) {
  const [rows, setRows] = useState([]);

  useEffect(() => {
    fetchRows({ userId, limit: 20 }).then(setRows); // built inside
  }, [userId]); // <- primitive dependency

  return <Table rows={rows} />;
}

Changed: the object is constructed inside the effect, and the dependency is the primitive userId. If the object must be shared, wrap it in useMemo with primitive deps.

Confirm it worked — Log the dependency identity: console.log(query) plus a render counter. If the object literal is gone from the dep array and the render count settles, the identity churn is gone.


3. setState called directly in the render body

Reproduce it

function Profile({ user }) {
  const [name, setName] = useState('');

  setName(user.name); // unconditional write during render

  return <h1>{name}</h1>;
}

Why it happens — A state write during render schedules an immediate re-render of the same component. React permits this only when it converges - when the setter is called with the current value it bails out. Unconditional writes never converge.

The fix

function Profile({ user }) {
  const [name, setName] = useState('');

  if (name !== user.name) {
    setName(user.name); // converges: next render the condition is false
  }

  return <h1>{name}</h1>;
}

Changed: added the equality guard. Better still, drop the state entirely and render user.name directly - derived values rarely need to be stored.

Confirm it worked — Remove the state and render the prop. If the error disappears, the state was derived and the guard was treating a symptom.


4. onClick wired to a call instead of a function

Reproduce it

function Row({ id }) {
  const [open, setOpen] = useState(false);

  // invoked during render, not on click
  return <button onClick={setOpen(!open)}>Toggle</button>;
}

Why it happens — onClick={setOpen(!open)} calls the setter while building the element and passes its return value as the handler. Every render fires a state update, so every render causes another render.

The fix

function Row({ id }) {
  const [open, setOpen] = useState(false);

  return <button onClick={() => setOpen(o => !o)}>Toggle</button>;
}

Changed: wrapped the call in an arrow function so it runs on click. The missing () => is the whole bug.

Confirm it worked — Reload without clicking anything. No error before the first click means the handler is no longer firing during render.


5. componentDidUpdate sets state with no guard

Reproduce it

class Chart extends React.Component {
  state = { width: 0 };

  componentDidUpdate() {
    this.setState({ width: this.node.offsetWidth });
  }

  render() {
    return <div ref={n => (this.node = n)} style={{ width: this.state.width }} />;
  }
}

Why it happens — componentDidUpdate runs after every commit. An unconditional setState there commits again and calls the lifecycle again. This is the exact pattern the error message names.

The fix

class Chart extends React.Component {
  state = { width: 0 };

  componentDidUpdate(prevProps, prevState) {
    const width = this.node.offsetWidth;
    if (width !== prevState.width) {
      this.setState({ width }); // only when it actually changed
    }
  }

  render() {
    return <div ref={n => (this.node = n)} style={{ width: this.state.width }} />;
  }
}

Changed: compare against prevState before writing, so the second pass is a no-op.

Confirm it worked — Put console.count('didUpdate') in the lifecycle. The count should stop growing a render or two after any prop change.


6. Effect depends on state it also writes

Reproduce it

function Cart({ items }) {
  const [total, setTotal] = useState(0);

  useEffect(() => {
    setTotal(items.reduce((a, i) => a + i.price, 0));
  }, [items, total]); // writes `total`, depends on `total`

  return <b>{total}</b>;
}

Why it happens — The effect writes the same value it watches. Even when the number is identical React may have already scheduled the render before bailing out, and if the value is an object it never bails out at all.

The fix

function Cart({ items }) {
  const total = useMemo(
    () => items.reduce((a, i) => a + i.price, 0),
    [items]
  );

  return <b>{total}</b>;
}

Changed: a value computed from props is not state. useMemo removes the write, and with it the loop.

Confirm it worked — Grep the effect body for the setter whose state is also in the dep array. Zero matches means this class of loop is gone.


More causes (4 remaining)

7. Parent passes a new callback, child effect depends on it

Reproduce it

function Parent() {
  const [n, setN] = useState(0);
  return <Child onReady={() => setN(n + 1)} />; // new function each render
}

function Child({ onReady }) {
  useEffect(() => { onReady(); }, [onReady]);
  return null;
}

Why it happens — The arrow function is a new identity on every parent render, so the child's effect reruns, calls onReady, re-renders the parent, and hands down a new function again.

The fix

function Parent() {
  const [n, setN] = useState(0);
  const onReady = useCallback(() => setN(c => c + 1), []); // stable
  return <Child onReady={onReady} />;
}

function Child({ onReady }) {
  useEffect(() => { onReady(); }, [onReady]);
  return null;
}

Changed: useCallback with an empty dep array plus the updater form keeps the identity stable across renders.

Confirm it worked — In the child, log the prop identity: useEffect(() => console.log('onReady changed'), [onReady]). It should fire once.


8. Context provider value rebuilt every render

Reproduce it

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);

  // new object identity on every render
  return (
    <AuthContext.Provider value={{ user, setUser }}>
      {children}
    </AuthContext.Provider>
  );
}

function Gate() {
  const auth = useContext(AuthContext);
  useEffect(() => { auth.setUser(readSession()); }, [auth]);
  return null;
}

Why it happens — Consumers see a new context value each render. Any consumer effect depending on that value reruns, writes provider state, re-renders the provider, and mints another value.

The fix

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const value = useMemo(() => ({ user, setUser }), [user]); // setUser is stable

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

function Gate() {
  const { setUser } = useContext(AuthContext);
  useEffect(() => { setUser(readSession()); }, [setUser]);
  return null;
}

Changed: memoised the provider value, and the consumer destructures the stable setter instead of depending on the whole object.

Confirm it worked — Log in the consumer effect. One entry per real user change, not one per render.


9. Store selector returns a fresh object each call

Reproduce it

// react-redux
function Header() {
  // new object every invocation -> reference check always fails
  const { name, avatar } = useSelector(s => ({
    name: s.user.name,
    avatar: s.user.avatar,
  }));

  return <img alt={name} src={avatar} />;
}

Why it happens — useSelector compares results by reference by default. An object literal never compares equal, so the component re-renders on every store notification - and if anything in the subtree dispatches on render, that becomes a loop.

The fix

function Header() {
  const name = useSelector(s => s.user.name);     // primitives
  const avatar = useSelector(s => s.user.avatar);

  return <img alt={name} src={avatar} />;
}

Changed: select primitives separately so the default reference check succeeds. Alternatively keep one selector and pass shallowEqual from react-redux as the second argument.

Confirm it worked — Dispatch an unrelated action. The component should not re-render - check with React DevTools' "Highlight updates when components render" option.


10. Router navigation triggered during render

Reproduce it

function Protected({ user }) {
  const navigate = useNavigate(); // react-router

  if (!user) {
    navigate('/login'); // side effect during render
  }

  return <Dashboard />;
}

Why it happens — navigate updates router state, which re-renders this component, which navigates again. The guard looks conditional but user never changes as a result of navigating, so the condition stays true.

The fix

function Protected({ user }) {
  if (!user) {
    return <Navigate to="/login" replace />; // declarative redirect
  }

  return <Dashboard />;
}

Changed: return a <Navigate> element instead of calling the imperative API during render. If you need the imperative form, move it into useEffect with [user, navigate] as deps.

Confirm it worked — Watch the address bar and the history length. A single transition to /login instead of a stream of entries means the loop is broken.

An orange cable is tangled on a sunlit wooden plank surface with shadows, creating a rustic and artistic look. ## None of Those? Narrow It Down
  1. Read the stack trace bottom-up and find the first frame inside your code, not inside react-dom. React reports where the limit was hit, which is often a child of the real culprit - the first application frame narrows it to a file.
  2. Install the react-hooks/exhaustive-deps lint rule and run it on that file. A warning means the dep array is the suspect; a clean file pushes you toward render-phase writes or lifecycle methods instead.
  3. Grep the component for setter calls that are not inside a function body: onClick={setX(...)}, a bare setX(...) at the top level of render, or setX in componentDidUpdate without an if. These rule in causes 3, 4, and 5 immediately.
  4. Add console.count('render') as the first line of the component. If the count climbs with no user interaction, the loop is in render or an effect; if it only climbs after a click, the handler is re-entering its own state.
  5. Comment out the effects one at a time. The one whose removal stops the error owns the loop - this isolates which dependency to inspect even when several effects write state.
  6. For the surviving effect, log every dependency with its identity: useEffect(() => console.log(deps), deps) style, or log typeof dep and whether it is an object. An object or function in the array that changes every render confirms causes 2, 7, 8, or 9.
  7. Check whether the state in question is derived from props or other state. If it can be computed with useMemo or inline, delete the state - the loop cannot exist without a write.
  8. If nothing in this component is guilty, open React DevTools, enable "Highlight updates when components render", and look for a flashing ancestor. A parent or context provider re-rendering continuously makes a correct child look broken.

Why This Error Exists At All

React's model is that rendering is a pure function of state and props. You change state, React calls your component, and the output is reconciled with the DOM. Nothing in that contract forbids a render from scheduling another render - effects and lifecycle methods exist precisely so you can react to what just rendered. The price of that flexibility is that a self-feeding cycle is a legal program, not a syntax error.

Without a limit, the cycle would spin inside React's work loop forever: the main thread never yields, the tab stops painting, and the only signal you get is a frozen browser with no stack trace. So React counts nested update depth - updates scheduled while processing another update - and throws once that count crosses a fixed threshold. The error is a circuit breaker, deliberately traded against the small risk of tripping on a legitimately deep but finite chain. It is not telling you the loop is infinite; it is telling you it got deep enough that React stopped assuming it would end.

The reason dependency arrays dominate the cause list is a second design decision: React compares dependencies with Object.is, a reference check, not a deep one. It has no way to know that { userId, limit: 20 } means the same thing as the object from the previous render, and deep comparison on every commit would be unbounded work. So identity stability became your responsibility, and every object, array, or function created in a render body is a potential loop generator. Once you see the error as "something in my dependency identity changes every render, or I am writing state during render," the entire family collapses into two questions - and that includes its cousins: Too many re-renders, Rendered more hooks than during the previous render, and the silent version where no error fires at all and the fan just spins up. Close-up view of colorful CSS and HTML code displayed on a dark computer screen.

Stop It From Coming Back

  • Enable eslint-plugin-react-hooks with react-hooks/exhaustive-deps set to error, not warn. It catches the missing and over-broad dependency arrays behind causes 1, 2, 6, and 7 before they reach a browser.
  • Treat derived values as computed, not stored: reach for useMemo or a plain inline expression before useState + useEffect. A loop needs a write, and derived state is the most common unnecessary write.
  • Memoise every context provider value with useMemo and every callback you pass down with useCallback, keyed on primitives. Make it a review checklist item for any file containing .Provider.
  • Guard all componentDidUpdate and getSnapshotBeforeUpdate state writes with an explicit prevProps/prevState comparison, and keep that comparison as the first statement so a reviewer can see it in one glance.
  • Select primitives in store hooks, or pass an explicit equality function - shallowEqual for react-redux, useShallow for Zustand. Never return a fresh object literal from a selector.
  • Add a React Testing Library test that mounts the component and asserts a render count, using a counter incremented in the component body under a test flag. A regression that reintroduces the loop fails the test instead of the production page.

Related Guides

Errors You Will Probably Hit Next

  • Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
  • Warning: Cannot update a component while rendering a different component
  • Error: Rendered more hooks than during the previous render.

Every instance of this error reduces to one of two questions: am I writing state during render, or does a dependency change identity on every render? Answer those in order and you will have the culprit before you finish reading the stack trace. When you do find the write, check whether the state needed to exist at all - deleting derived state fixes more of these loops than guarding them does.

댓글

이 블로그의 인기 게시물

TypeError: Cannot read properties of undefined (reading 'map') - 11 Causes and Fixes

psql: FATAL: password authentication failed for user - 10 Causes and Fixes

Error: ERR_MODULE_NOT_FOUND: Cannot find package - 10 Causes and Fixes