0
0
ReactDebug / FixBeginner · 4 min read

How to Fix 'Cannot Update During Render' Error in React

The cannot update during render error happens when you try to change state or props while React is rendering a component. To fix it, move state updates out of the render phase into event handlers or useEffect hooks so React can finish rendering first.
🔍

Why This Happens

This error occurs because React does not allow state updates while it is rendering a component. React's render phase should be pure and free of side effects like changing state. Updating state during render causes an infinite loop or inconsistent UI.

jsx
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  // This causes the error because setCount runs during render
  if (count === 0) {
    setCount(1);
  }

  return <div>Count: {count}</div>;
}

export default Counter;
Output
Error: Cannot update a component (`Counter`) while rendering a different component (`Counter`).
🔧

The Fix

To fix this, move the state update out of the render phase. Use useEffect to update state after the component renders, or trigger updates in event handlers. This keeps rendering pure and avoids the error.

jsx
import React, { useState, useEffect } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  // Update count after first render
  useEffect(() => {
    if (count === 0) {
      setCount(1);
    }
  }, []);

  return <div>Count: {count}</div>;
}

export default Counter;
Output
Count: 1
🛡️

Prevention

Always avoid calling state setters directly inside the main body of your component function. Instead:

  • Use useEffect for side effects and state updates after render.
  • Trigger state changes in event handlers like onClick.
  • Keep render functions pure and free of side effects.
  • Use linting tools like eslint-plugin-react-hooks to catch improper hook usage.
⚠️

Related Errors

Similar errors include:

  • Maximum update depth exceeded: Happens when state updates cause infinite re-renders.
  • Cannot update a component while rendering a different component: Occurs when a child component tries to update parent state during render.

Fixes usually involve moving state updates to useEffect or event handlers.

Key Takeaways

Never update state directly inside the render function of a React component.
Use useEffect to perform state updates after the component has rendered.
Trigger state changes in event handlers, not during rendering.
Keep render functions pure and free of side effects to avoid errors.
Use linting tools to catch improper hook and state update patterns early.