Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readReact
#React#Hooks#Debugging#Performance
3D illustration of a render loop of glowing component cubes circling a warning node

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:

tsx
'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:

tsx
const renders = useRef(0); renders.current += 1; console.log('render', renders.current, { filters, deps: [filters.q] });

Key Comparison Table

Source of the loopWhy it repeatsFix
setState in useEffect with object/array dependencyNew identity every renderDepend on primitives (filters.q), memoize the object
setState unconditionally in renderEvery render schedules anotherCompare with previous prop/state before setting
getSnapshot returns a fresh objectReact re-checks the snapshot foreverCache in a module variable, return primitives
Selector returning array.filter(...)New array each store readMemoize by store state, use useShallow
Context value={{ … }}Provider renders re-create the valueuseMemo the value, or split contexts
Router replace() in an effect keyed on search paramsString rebuilt each renderBuild the URL from primitives, compare first
HookLoop riskSafe pattern
useEffectHigh with non-primitive depsPrimitives, useMemo, useEffectEvent
useLayoutEffectSame, plus blocks paintSame rules, smaller surface
useSyncExternalStoreHigh with uncached snapshotStable reference or primitive snapshot
useReducerLowReducer must not dispatch a state-identical action in a loop
useState + useMemo chainMediumDerive during render instead of storing

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Effect that derives state from an object prop

tsx
// Broken useEffect(() => { setTotal(items.reduce((a, b) => a + b.price, 0)); }, [items]); // Parent renders <Cart items={[...cart.items, promo]} /> — a new array every time
tsx
// 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

tsx
// 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} />)}</>; }
tsx
// 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

tsx
// 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 }} />
tsx
// 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:

tsx
const onPick = useEffectEvent(() => select(id)); useEffect(() => { onPick(); }, []); // fires once, always sees fresh id

4. External store snapshots

tsx
// Broken: new array every call -> "getSnapshot should be cached" const snapshot = useSyncExternalStore(subscribe, () => Object.values(store.byId).filter((x) => x.active), );
tsx
// 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

tsx
// 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]);
tsx
// 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

MistakeWhy it loopsCorrect approach
setState in useEffect with [obj]New object identity per renderDepend on primitives
useCallback with an inline dependencyCallback recreated anyway
setState in render without a guardInfinite render chainCompare, then set
getSnapshot returning {} or []Snapshot never equalCache the reference
Using state for derived valuesTwo sources of truthCompute during render
Effect that fetches on every filters objectObject identity, not data, changesSerialize 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 tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.