React Maximum Update Depth Exceeded: Finding the Update Loop
Fifty nested updates and React gives up. The loop is always a new identity: an inline object in a dependency array, a setState in render, or a selector that returns a fresh array.

Introduction & Quick Summary
Symptom. 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. React 19 reports the same message with a component stack and, in a useSyncExternalStore case, the companion warning The result of getSnapshot should be cached to avoid an infinite loop. In development the error is thrown and the tree unmounts; in production the same loop often freezes the tab or hits the browser's "page unresponsive" prompt instead.
Cause. A render produces a value that causes another render, which produces the same cause again. Three shapes cover nearly every report: a setState call inside useEffect whose dependency array changes identity on every render (an inline object, array, or function), a setState call in the render body that is not guarded by a comparison, and a state value read through an unstable snapshot (getSnapshot returning a new object each call, a selector returning a new array, a context provider recreating value).
Fix. Make every dependency a primitive or a stable reference; wrap derived objects in useMemo, and callbacks in useEffectEvent when the effect only needs the latest callback. Guard render-phase updates by comparing with the previous value and committing inside the same render. For external stores, return the same reference until the underlying data changes.
Core Mechanics, Signatures & Reproducible Setup
React limits nested updates to 50 in development. An update during render is legal only when it converges: the "adjust state during render" pattern compares a prop to a stored previous value and calls the setter conditionally. An update inside useEffect is legal only when the dependency array is stable — React compares with Object.is, so a new object literal is a new dependency every render.
Reproduce the most common variant in one file:
'use client';
import { useEffect, useState } from 'react';
export function Filters({ initial }: { initial: string }) {
const [filters, setFilters] = useState({ q: initial }); // object state
const [rows, setRows] = useState<string[]>([]);
useEffect(() => {
// `filters` is a new object each render only if you recreate it;
// here the loop comes from the effect's own setState on `filters`
setFilters({ q: filters.q.toUpperCase() });
}, [filters]);
return <p>{rows.length} rows for {filters.q}</p>;
}Each pass sets filters to a new object with a value that is already equal as a string but different as a reference, so the effect fires again. The console fills with the error within a few milliseconds. The same failure appears when a parent passes style={{ margin: 8 }}, items={[]}, or onSelect={() => …} to a child whose effect depends on it.
Diagnose it without guessing. The component stack in the error names the component, but not the update. Add a render counter and log the dependency values, then look for the argument whose Object.is result changes every pass:
const renders = useRef(0);
renders.current += 1;
console.log('render', renders.current, { filters, deps: [filters.q] });Key Comparison Table
| Source of the loop | Why it repeats | Fix |
|---|---|---|
setState in useEffect with object/array dependency | New identity every render | Depend on primitives (filters.q), memoize the object |
setState unconditionally in render | Every render schedules another | Compare with previous prop/state before setting |
getSnapshot returns a fresh object | React re-checks the snapshot forever | Cache in a module variable, return primitives |
Selector returning array.filter(...) | New array each store read | Memoize by store state, use useShallow |
Context value={{ … }} | Provider renders re-create the value | useMemo the value, or split contexts |
Router replace() in an effect keyed on search params | String rebuilt each render | Build the URL from primitives, compare first |
| Hook | Loop risk | Safe pattern |
|---|---|---|
useEffect | High with non-primitive deps | Primitives, useMemo, useEffectEvent |
useLayoutEffect | Same, plus blocks paint | Same rules, smaller surface |
useSyncExternalStore | High with uncached snapshot | Stable reference or primitive snapshot |
useReducer | Low | Reducer must not dispatch a state-identical action in a loop |
useState + useMemo chain | Medium | Derive during render instead of storing |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Effect that derives state from an object prop
// Broken
useEffect(() => { setTotal(items.reduce((a, b) => a + b.price, 0)); }, [items]);
// Parent renders <Cart items={[...cart.items, promo]} /> — a new array every time// Fixed A — derive during render, no state at all
const total = useMemo(() => items.reduce((a, b) => a + b.price, 0), [items]);
// Fixed B — memoize at the parent so identity is stable
const items = useMemo(() => [...cart.items, promo], [cart.items, promo]);Storing derived data in state is the root cause more often than the dependency array. If the value can be computed from props, compute it.
2. Render-phase updates: the supported form
// Broken: unbounded
function List({ items }: { items: Item[] }) {
const [sorted, setSorted] = useState(items);
setSorted([...items].sort(byName)); // new array every render
return <>{sorted.map((i) => <Row key={i.id} item={i} />)}</>;
}// Fixed: adjust only when the input actually changed
function List({ items }: { items: Item[] }) {
const [prev, setPrev] = useState(items);
const [sorted, setSorted] = useState(() => [...items].sort(byName));
if (items !== prev) {
setPrev(items);
setSorted([...items].sort(byName));
}
return <>{sorted.map((i) => <Row key={i.id} item={i} />)}</>;
}React allows this because the update happens during render and converges: the second render sees items === prev and stops. An unconditional setter here is the bug.
3. Unstable props from a memoized child
// Broken: memo does nothing, child effect loops
const Row = memo(function Row({ onPick, style }: Props) {
useEffect(() => { onPick(); }, [onPick]); // new function each parent render
return <div style={style} />;
});
<Row onPick={() => select(id)} style={{ padding: 4 }} />// Fixed: stable callback + hoisted style
const onPick = useCallback(() => select(id), [id]);
const ROW_STYLE = { padding: 4 };
<Row onPick={onPick} style={ROW_STYLE} />useEffectEvent (React 19) is the better answer when the effect needs the latest callback but must not re-run for it:
const onPick = useEffectEvent(() => select(id));
useEffect(() => { onPick(); }, []); // fires once, always sees fresh id4. External store snapshots
// Broken: new array every call -> "getSnapshot should be cached"
const snapshot = useSyncExternalStore(subscribe, () =>
Object.values(store.byId).filter((x) => x.active),
);// Fixed: cache the derived value against the store version
let cache: Active[] = [];
let cacheVersion = -1;
function getActive() {
if (cacheVersion !== store.version) {
cache = Object.values(store.byId).filter((x) => x.active);
cacheVersion = store.version;
}
return cache;
}
const snapshot = useSyncExternalStore(subscribe, getActive, () => EMPTY);Zustand's useShallow and Redux's createSelector do the same job. The rule is not "avoid arrays" — it is "return the same reference while the data is unchanged".
5. Search params and router updates in an effect
// Broken: object rebuilt from the router every pass, replace triggers a render
'use client';
const params = useSearchParams();
useEffect(() => {
const next = new URLSearchParams(params);
next.set('page', '1');
router.replace(`/list?${next}`);
}, [params, router]);// Fixed: depend on the string, compare before navigating
const qs = useSearchParams().toString();
useEffect(() => {
const next = new URLSearchParams(qs);
if (next.get('page') === '1') return;
next.set('page', '1');
router.replace(`/list?${next.toString()}`);
}, [qs, router]);router is stable in the App Router, but useSearchParams() is not guaranteed to keep identity across renders in every version. A string dependency plus an equality guard is version-proof.
Common Compilation/Runtime Mistakes & Version Gotchas
| Mistake | Why it loops | Correct approach |
|---|---|---|
setState in useEffect with [obj] | New object identity per render | Depend on primitives |
useCallback with an inline dependency | Callback recreated anyway | |
setState in render without a guard | Infinite render chain | Compare, then set |
getSnapshot returning {} or [] | Snapshot never equal | Cache the reference |
| Using state for derived values | Two sources of truth | Compute during render |
Effect that fetches on every filters object | Object identity, not data, changes | Serialize to a string key |
Version notes: React 18's automatic batching means several loop iterations can happen inside one paint, so the error can appear instantly instead of after a visible flicker — do not read "it happened at once" as a different bug. React 19's StrictMode double-invokes effects in development, which turns an effect that sets state on mount from "runs twice" into a visible loop only when the dependency is unstable; the double invocation is not the cause. React 19 also deprecates componentWillUpdate-era class lifecycles mentioned in the message — if you are on classes, move the update into componentDidUpdate with an explicit value comparison, since the same rule applies. With React Compiler enabled, the compiler adds memoization automatically, which can hide a loop in one component and expose it in the next; keep dependency arrays explicit rather than relying on it.
To compare two state dumps taken a render apart, paste them into the JSON formatter and inspect with the text diff tool; a diff whose only change is a key order or a regenerated id is the usual confirmation that the identity, not the data, is moving.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact Profiler API: Measuring Render Timings and Identifying Wasted Re-Renders
actualDuration versus baseDuration, phase names that tell you who triggered a commit, and how to ship the numbers without flooding a backend.
React with TypeScript: Generic Components, PropsWithChildren, and Event Types
Generic props that infer from data, PropsWithChildren instead of React.FC, and element-scoped event types that keep currentTarget typed.
React useTransition and useDeferredValue: Non-Blocking Concurrent UI Updates
Transitions let React throw away background work when typing arrives. Which hook defers what, and why a controlled input must never be transitioned.
React.lazy and Code Splitting: Route Chunks, Preloading, and Suspense
Where the split points belong, how to preload on intent, and how to recover when a stale chunk 404s after a deployment.
More in React
All React guidesThe guides filed next to this one in React, in library order.