🔧 Error Fixes

Fix: React — Cannot update a component while rendering a different component


Warning: Cannot update a component (`Parent`) while rendering
a different component (`Child`).

You’re calling setState (or a dispatch) during the render phase of another component. React doesn’t allow this.

Fix 1: Move setState into useEffect

// ❌ Setting parent state during child render
function Child({ onMount }) {
  onMount('ready');  // Calls parent setState during render!
  return <div>Child</div>;
}

// ✅ Use useEffect
function Child({ onMount }) {
  useEffect(() => {
    onMount('ready');
  }, []);
  return <div>Child</div>;
}

Fix 2: Don’t call setState in render body

// ❌ setState called during render
function MyComponent({ data }) {
  const [items, setItems] = useState([]);
  setItems(data.filter(d => d.active));  // Called every render!

  // ✅ Use useMemo instead
  const items = useMemo(
    () => data.filter(d => d.active),
    [data]
  );

  return <ul>{items.map(i => <li key={i.id}>{i.name}</li>)}</ul>;
}

Fix 3: Wrap callbacks properly

// ❌ Calling the function immediately
<button onClick={setCount(count + 1)}>  {/* Runs during render! */}

// ✅ Wrap in arrow function
<button onClick={() => setCount(count + 1)}>

The rule

Never call setState, dispatch, or any state-updating function directly in the render body. Use useEffect for side effects, useMemo for derived values, and arrow functions for event handlers.

See also: React too many re-renders fix | React Hooks cheat sheet