Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React: Cannot update a component while rendering a different component

The warning means one component scheduled state for another during render. Derive the value or move the write to a handler.

~6 min readReact
#React#State#Hooks#Debugging
Two component blocks with a state plug trying to cross between them and an amber warning plate

Introduction & Quick Summary

The console prints Warning: Cannot update a component (CartBadge) while rendering a different component (ProductCard). To locate the bad setState() call inside ProductCard, follow the stack trace as described in https://react.dev/link/setstate-in-render. The UI may look correct in development and then update late, drop an update, or loop under React's concurrent rendering.

The message is precise about the shape of the bug: component A calls a state setter that belongs to component B during A's render phase. React notices that a render is scheduling work for another component, which breaks the assumption that a render is a pure function of props and state. In React 18 and 19 the warning can precede a real correctness problem: the update is applied after the current render, so a render may be committed with stale data, and in a transition it can be discarded or replayed.

Almost every case reduces to one of four patterns:

  1. A child writes to the parent instead of calling a callback after an event.
  2. A component copies a prop into state during render (useState(props.value)) and "syncs" it by calling the parent's setter.
  3. A context or store provider calls its own setter inside its render body.
  4. A library - a router, a form library, a chart - sets state while rendering a component you control.

The fixes are local: move the write into an event handler, into useEffect, or replace the state with a value derived during render. The rest of this guide shows the mechanics, a comparison of where each update belongs, and six concrete refactors with code.

Core Mechanics, Signatures & Reproducible Setup

React's render phase must be side-effect free. A function component may compute values and return elements, but it may not mutate external state, because React may call it more than once, may not commit the result, and may interleave it with other work. setState from useState (and the dispatch from useReducer) schedules an update for a specific fiber. Calling it from within the render of a different fiber violates that contract, and React reports it through the warning above in development builds.

Recreate the warning without any library in a two-component file:

tsx
// repro.tsx import { useState } from "react"; function Parent({ count }: { count: number }) { const [total, setTotal] = useState(0); if (count > 0) setTotal(count); // WRONG: updates another component during render return <p>{total}</p>; } export function App() { const [count, setCount] = useState(0); return ( <> <button onClick={() => setCount((c) => c + 1)}>add</button> <Parent count={count} /> </> ); }

The two sanctioned alternatives, both visible from the call sites:

tsx
// 1. Derive during render in the same component function Parent({ count }: { count: number }) { return <p>{count}</p>; } // 2. Adjust state during render, but only for this component's own state function Parent({ count }: { count: number }) { const [shown, setShown] = useState(0); const [prevCount, setPrevCount] = useState(count); if (count !== prevCount) { setPrevCount(count); setShown(count); } return <p>{shown}</p>; }

The second pattern is the one React documents for adjusting state when a prop changes: the component updates its own state during render, then re-renders before committing. Updating another component is still wrong, and that is what the warning is about.

Key Comparison Table

Where the update happensWarningCorrectnessRecommended
Event handler in the owning componentnoneupdates commit after the eventyes, default
useLayoutEffect writing to a parentnonesynchronous before paintonly for measurement
useEffect writing to a parentnoneone extra render, after paintyes for external sync
During render, own statenoneimmediate re-renderyes, for prop-derived state
During render, another componentyesmay commit stale or dropnever
During render, in a reducernonereducer must stay purereducers must be pure
In a ref callbacknoneruns on mount and changefine for focus and measurement
SymptomLikely patternFix
Badge updates one render lateparent setter called from child renderpass a callback, call it in the handler
Infinite "maximum update depth"derived state written in an effect that changes its own dependencyderive with a variable instead
Warning only on first mountinitialising parent state from a child's propslift the state, or render from the prop
Warning only in StrictModethe render runs twice by designthe bug is present in production too
Warning from a library, not your codelibrary sets state in renderupgrade, or isolate behind a wrapper

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Child-to-parent writes: replace with a callback

The most common instance: a child computes something during render and calls props.setValue so the parent can display it. Pass the computed value up only when the user acts, and derive the display value in the parent render:

tsx
function QuantityInput({ value, onChange }: { value: number; onChange: (n: number) => void }) { return <input value={value} onChange={(e) => onChange(Number(e.target.value))} />; } function Cart({ price }: { price: number }) { const [quantity, setQuantity] = useState(1); const total = price * quantity; // derived, never stored return ( <> <QuantityInput value={quantity} onChange={setQuantity} /> <p>{total}</p> </> ); }

2. Prop copied into state, then synced

useState(props.value) is a legitimate way to give an input an initial value, but syncing it with useEffect(() => setState(props.value), [props.value]) introduces a render where the component shows the old value, and a parent callback in that effect escalates to the warning. Choose one:

tsx
// uncontrolled after mount, remount when the identity changes <Editor key={doc.id} initialBody={doc.body} onSave={save} /> // fully controlled, no internal copy <Editor body={doc.body} onChange={(b) => update(doc.id, b)} />

The key is the honest signal: a different document is a different component instance, so its state should not survive.

3. Talk to a parent in an effect, not in render

When a child genuinely must inform the parent after commit - measuring its height, reporting focus - do it in an effect and guard against redundant updates:

tsx
function Child({ onHeight }: { onHeight: (h: number) => void }) { const ref = useRef<HTMLDivElement>(null); useLayoutEffect(() => { const h = ref.current?.getBoundingClientRect().height ?? 0; onHeight((prev) => (prev === h ? prev : h)); // bail out when unchanged }, [onHeight]); return <div ref={ref} />; }

The functional bail-out prevents a second render from an identical value, which is the usual source of a "maximum update depth exceeded" follow-on.

4. Context providers that set state during render

A provider that stores "last value" and writes it in its own render body triggers the same warning against its children. Context values should be computed with useMemo, not with state:

tsx
const ThemeContext = createContext<Theme>("light"); export function ThemeProvider({ mode, children }: { mode: Theme; children: ReactNode }) { const value = useMemo(() => mode, [mode]); return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>; }

If the provider must react to a child's report, expose a setter through context and call it only from event handlers.

5. Stores and routers: useSyncExternalStore instead of writing on render

An external store that notifies subscribers during render is the same violation with a library-shaped stack. Subscribe with useSyncExternalStore, which is designed to read an external snapshot during render without setState:

tsx
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);

For routers, the warning usually means a redirect was triggered during render (navigate() called in a render body). Move it into an effect or a route loader, and gate it on "not already on that route" so it fires once.

6. Confirming which component actually wrote

The stack trace in the warning points at the child, not the offender, so measure before fixing: wrap the subtree in <React.Profiler> and export the commit data, then look for a component that renders twice per interaction:

tsx
<React.Profiler id="cart" onRender={(id, phase, dur) => console.log(id, phase, dur)}> <Cart /> </React.Profiler>

A capture that shows update immediately followed by update for the same component is the render-phase write. Paste the exported profiler JSON into JSON Formatter to read the commit order without a console.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Wrapping the call in React.startTransition or flushSync. Both keep the setState inside a render. The warning may be replaced by an error under StrictMode; the bug remains.
  • Moving it to useLayoutEffect as a blanket fix. It removes the warning but adds a synchronous layout read and a second render; use it only for measurement.
  • Blaming StrictMode. Double invocation in development exposes the impurity; production can still drop or replay the update in concurrent rendering.
  • Ignoring it because the UI looks right. In React 18+ a render may be thrown away, and the abandoned update can leave a cache or a controlled input out of sync.
  • Library warnings treated as noise. A chart or form library that sets state in render is a real defect; pin the version that fixes it or wrap the component so the state lives outside.
  • React 19 changes. The message text and stack format differ from React 18 and react.dev/link/setstate-in-render now redirects to the errors page; the rule is unchanged and the warning still appears only in development builds.

Primary references: You Might Not Need an Effect documents deriving values during render and the narrow case for adjusting a component's own state, and the useState reference states the purity rule that the warning enforces.

Official references

primary documentation

The React documentation that defines the behaviour this guide explains.

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.