react render_error ai_generated true

Cannot update a component while rendering a different component

ID: react/cannot-update-while-rendering

Also available as: JSON · Markdown
82%Fix Rate
85%Confidence
205Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
18 active

Root Cause

State update triggered during render phase of another component. Usually setState in render body.

generic

Workarounds

  1. 90% success Move the state update into useEffect
    useEffect(() => { setState(value); }, [dependency]);

    Sources: https://react.dev/reference/react/useEffect

  2. 82% success Restructure to lift state up or use a shared context
    // Lift state to the common parent:
    function Parent() {
      const [shared, setShared] = useState(init);
      return <><ChildA value={shared} /><ChildB onChange={setShared} /></>;
    }

    Sources: https://react.dev/learn/sharing-state-between-components

Dead Ends

Common approaches that don't work:

  1. Wrap the update in setTimeout 65% fail

    Hacky fix that can cause flickering and race conditions

  2. Use useLayoutEffect for the update 60% fail

    May cause the same issue if the update triggers a re-render

Error Chain

Leads to:
Preceded by:
Frequently confused with: