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.

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:
- A child writes to the parent instead of calling a callback after an event.
- A component copies a prop into state during render (
useState(props.value)) and "syncs" it by calling the parent's setter. - A context or store provider calls its own setter inside its render body.
- 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:
// 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:
// 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 happens | Warning | Correctness | Recommended |
|---|---|---|---|
| Event handler in the owning component | none | updates commit after the event | yes, default |
| useLayoutEffect writing to a parent | none | synchronous before paint | only for measurement |
| useEffect writing to a parent | none | one extra render, after paint | yes for external sync |
| During render, own state | none | immediate re-render | yes, for prop-derived state |
| During render, another component | yes | may commit stale or drop | never |
| During render, in a reducer | none | reducer must stay pure | reducers must be pure |
| In a ref callback | none | runs on mount and change | fine for focus and measurement |
| Symptom | Likely pattern | Fix |
|---|---|---|
| Badge updates one render late | parent setter called from child render | pass a callback, call it in the handler |
| Infinite "maximum update depth" | derived state written in an effect that changes its own dependency | derive with a variable instead |
| Warning only on first mount | initialising parent state from a child's props | lift the state, or render from the prop |
| Warning only in StrictMode | the render runs twice by design | the bug is present in production too |
| Warning from a library, not your code | library sets state in render | upgrade, 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:
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:
// 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:
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:
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:
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:
<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.startTransitionorflushSync. Both keep the setState inside a render. The warning may be replaced by an error under StrictMode; the bug remains. - Moving it to
useLayoutEffectas 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-rendernow 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 documentationThe React documentation that defines the behaviour this guide explains.
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: An update inside a test was not wrapped in act(...)
The warning means a state update escaped the test's act scope. Await the interaction, use findBy queries, and wrap manual updates properly.
react-hook-form with zod 4: resolver type errors after the upgrade
Zod 4 split input from output and resolvers v5 re-typed Resolver. Drop the generic, or pass all three, and the errors disappear.
React Compiler: Cannot reassign variable after render completes
The immutability rule flags a closure that writes a render-scoped value. Decide whether it is a real bug, a false positive, or a bailout.
React: Too many re-renders. React limits the number of renders
A setter runs during render and schedules another render. Fix the invoked handler, the unstable dependency, or the prop-to-state copy.
More in React
All React guidesThe guides filed next to this one in React, in library order.