12k
All articles

Fixing “Too Many Re-Renders” in React

Fix the React Too many re-renders error by finding render-time state setters, correcting event handlers, guarding prop updates, and distinguishing effect loops.

OpenReplay Team
OpenReplay Team
Fixing “Too Many Re-Renders” in React

“Too many re-renders” means a component called a state setter while it was rendering. Every render queued another render, so React stopped the loop by throwing an error instead of letting the page hang.

The usual story: you changed one line, the screen went blank, and the console now points at a component that worked a minute ago.

This article covers the four render-phase causes of the error, with a broken and a fixed version of each. It also shows how to tell this error apart from the effect loop that produces a different message. The examples use function components and hooks on React 19.

Key Takeaways

  • “Too many re-renders” is a render-phase error: a setter runs while the component body executes, and every retry runs it again.
  • You can set state from props during render only behind a condition that turns false after the update, such as comparing the current prop with a stored copy of the previous one.
  • If a value can be calculated from props or existing state, calculate it during render. With no state to sync, there is no setter left to loop.
  • A guard that compares a newly created array or object with the one in state passes on every render, so it never stops the loop.
  • A useEffect that keeps setting state loops after commit. In development, React typically warns “Maximum update depth exceeded” for that case instead.

What Does “Too Many Re-Renders” Mean in React?

The React “Too many re-renders” error means a state update ran during render on every pass, so the render could never finish. The full message reads:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

Production builds shorten it to minified React error #301.

React does allow a setter call during render, but only for a narrow pattern. When the call happens, React throws away the JSX the component just returned and re-runs it immediately. If the setter runs again on the retry, React retries again. After a fixed internal limit, React throws. The deeper rule is that rendering should be pure: render calculates JSX and does not change state that triggers more rendering.

Cause 1: A Setter in the Component Body

A state setter called at the top level of a component body runs on every render, so the loop can never stop.

// Broken
function Counter() {
  const [count, setCount] = useState(0);
  setCount(count + 1);
  return <p>{count}</p>;
}

// Fixed: start from the value you need
function Counter() {
  const [count, setCount] = useState(1);
  return <p>{count}</p>;
}

If the starting value takes work to compute, pass a lazy initialiser such as useState(() => computeStart()). The companion guide on fixing “Maximum update depth exceeded” in React covers this case and Cause 2 in more detail.

Cause 2: Calling the Event Handler Instead of Passing It

Writing onClick={handleClick()} calls the function during render and passes its return value to onClick. Writing onClick={handleClick} or onClick={() => setCount(1)} passes a function, and React calls it only when the click happens.

// Broken: setCount runs during render
<button onClick={setCount(count + 1)}>Add</button>

// Fixed: React calls the arrow function on click
<button onClick={() => setCount((c) => c + 1)}>Add</button>

React’s guide to responding to events shows the same distinction. The rule also applies to onSubmit and to form actions. If your form uses useActionState, pass the action it returns to the form and don’t call it in JSX.

Cause 3: Setting State From Props During Render

Setting state from a prop during render works only behind a condition that turns false after the update. The usual condition compares the current prop with a copy of the previous prop kept in state. Without that condition, the update runs on every pass.

// Broken: both setters run on every render
function SelectableList({ items }) {
  const [selection, setSelection] = useState(null);
  const [prevItems, setPrevItems] = useState(items);
  setPrevItems(items);
  setSelection(null);
  // ...
}

The guarded version follows the pattern React documents for storing information from previous renders:

import { useState } from 'react';

function SelectableList({ items }) {
  const [selection, setSelection] = useState(null);
  const [prevItems, setPrevItems] = useState(items);

  if (items !== prevItems) {
    setPrevItems(items);
    setSelection(null);
  }
  // ...
}

After the update, prevItems and items hold the same reference. On the retry the condition is false, and the loop ends after one extra pass.

The better fix usually removes the synced state altogether. React’s page on adjusting some state when a prop changes recommends this: store the minimum, then calculate everything else.

import { useState } from 'react';

function SelectableList({ items }) {
  const [selectedId, setSelectedId] = useState(null);
  const selection = items.find((item) => item.id === selectedId) ?? null;
  // ...
}

When the list changes and the selected item is no longer in it, selection becomes null without any reset. With no setter in the render path, nothing can loop.

Cause 4: A Guard That Never Closes

A guard that compares a newly created array or object with the one in state passes on every render. Each render builds a new reference, so the setter keeps running. React compares state values with Object.is, and two arrays with identical contents are still different values.

// Broken: `next` is a new array every render
function TagList({ tags }) {
  const [normalized, setNormalized] = useState([]);
  const next = tags.map((t) => t.trim().toLowerCase());
  if (next !== normalized) setNormalized(next);
  // ...
}

The condition looks like the guard from Cause 3, but it checks the output of a calculation instead of its input. Drop the state and calculate the value:

import { useMemo } from 'react';

function TagList({ tags }) {
  const normalized = useMemo(
    () => tags.map((t) => t.trim().toLowerCase()),
    [tags]
  );
  // ...
}

Use useMemo only if the calculation is expensive. A plain const works too. If you really need state, guard on the source prop (tags !== prevTags) and not on the derived array.

Not This Error: Effect Loops and “Maximum Update Depth Exceeded”

An effect loop is a different error from “Too many re-renders”, which comes from the render phase. A useEffect that keeps setting state loops after React commits to the screen. For that case, React typically warns “Maximum update depth exceeded” in the development console.

// Loops after every commit: no dependency array
useEffect(() => {
  setCount(count + 1);
});

// Runs once after mount
useEffect(() => {
  setCount((c) => c + 1);
}, []);

React’s useEffect troubleshooting entry on effects that re-run in an infinite cycle covers dependency fixes. Often the best fix is the same as in Cause 3: calculate the value and remove the effect.

Too many re-rendersMaximum update depth exceeded
When the loop runsDuring render, before anything is committedAfter commit, in effects
Typical causeSetter called in the component body or JSXuseEffect setting state with missing or always-changing deps
Where the stack pointsThe looping component, named in the stack and component stackA development warning naming the component, or a thrown stack through the setter
Fix directionRemove or guard the render-time update, or calculate the valueFix the dependency array or calculate the value

“Maximum update depth exceeded” is also thrown as minified error #185 for nested synchronous updates. It doesn’t always throw.

“Too many re-renders” and an effect loop also look different on screen. A render loop throws, and React removes the UI from the screen unless an error boundary catches the error. In production, session replay shows that blank or frozen component next to the console error. This helps you find the loop when it only happens for certain props.

A Quick Checklist for Finding the Offending Call

When you hit “Too many re-renders”, the stack and component stack name the component that’s looping. Check that component’s body for a setter that runs during render:

  1. Confirm the message. “Too many re-renders” points to render. “Maximum update depth exceeded” points to effects or nested updates.
  2. Open the component named in the component stack.
  3. Search the component body, outside effects and handlers, for every set call.
  4. Search the JSX for handler props followed by (), such as onClick={fn()}.
  5. For each guarded setter, check that the condition compares a stable input (a prop or primitive) and not a new array or object.
  6. Ask whether the stored value can be calculated instead. If so, delete the state.
  7. Check custom hooks called by the component, since a setter can sit one layer down.

Fixing the Loop for Good

Every case of “Too many re-renders” comes from a setter that runs during render and runs again on each retry. Find that call, then remove it, add a guard that turns false, or calculate the value instead of storing it. If the stack shows the same frames repeating outside React’s render cycle, you are looking at plain recursion. The guide to fixing “Maximum call stack size exceeded” in JavaScript covers that case.

FAQs

Can an error boundary catch the Too many re-renders error?

Yes. The error is thrown during rendering, so the nearest error boundary above the looping component catches it and shows its fallback instead of blanking the whole root. The boundary must be a class component that defines static getDerivedStateFromError, or you can use the react-error-boundary package. A boundary only hides the symptom. The setter that runs during render still has to be removed or guarded.

Does writing useState(computeValue()) cause too many re-renders?

No. Writing useState(computeValue()) calls computeValue on every render, but it calls no setter, so it cannot loop. React uses the result only on the first render and ignores it afterwards, which wastes work if the function is expensive. Pass the function itself, as in useState(computeValue), and React calls it only once to create the initial state.

How do I debug minified React error 301 in production?

Minified React error 301 is the production form of Too many re-renders. Production builds replace the full message with a short code and a link to react.dev/errors/301. To find the looping component, reproduce the issue with a development build, which shows the full message and a component stack naming the component. Then check that component's body and JSX for a setter that runs during render.

DevTools for the frontend

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.