πŸ”§ Error Fixes
Β· 1 min read

React: Cannot Update During an Existing State Transition


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-deps catches many of these patterns.

Related: React complete guide Β· React Interview Questions Β· React: Rendered Fewer Hooks Than Expected Fix

πŸ“˜