Warning: Cannot update during an existing state transition
Youβre calling setState during render β usually inside the component body instead of in an event handler or useEffect.
Why this happens
Reactβs render phase should be pure β no side effects. When you call setState directly in the component body, it triggers a re-render while the current render is still in progress. This creates an infinite loop or unpredictable behavior, so React warns you. It commonly happens when deriving state from props without useEffect.
Fix 1: Move setState to useEffect
// β Setting state during render
function Component({ value }) {
setCount(value); // Triggers re-render during render!
return <div>{count}</div>;
}
// β
Use useEffect
function Component({ value }) {
useEffect(() => {
setCount(value);
}, [value]);
return <div>{count}</div>;
}
Fix 2: Donβt call setState in render logic
// β Calling setState in a condition during render
if (items.length > 0) {
setHasItems(true); // Bad!
}
// β
Derive the value instead
const hasItems = items.length > 0;
Alternative solution: Use useMemo for derived values
If youβre syncing state from props, you probably donβt need state at all:
// β
Derive directly β no state needed
const filteredItems = useMemo(
() => items.filter(i => i.active),
[items]
);
Prevention
- Follow the rule: if a value can be computed from props or other state, donβt store it in state.
- Use the React ESLint plugin β
react-hooks/exhaustive-depscatches many of these patterns.
Related: React complete guide Β· React Interview Questions Β· React: Rendered Fewer Hooks Than Expected Fix