You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
$ pnpm eslint . --max-warnings 0
/project/workspace/app/Component.tsx
7:5 error Error: Calling setState synchronously within an effect can trigger cascading renders
Effects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:
* Update external systems with the latest state from React.
* Subscribe forupdates from some external system, calling setStatein a callback functionwhen external state changes.
Calling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).
/project/workspace/app/Component.tsx:7:5
5 |
6 |useEffect(() => {
> 7 | setDidMount(true);| ^^^^^^^^^^^ Avoid calling setState() directly within an effect
8 | }, []);
9 |
10 |return<div>Mounted: {didMount ?"Yes":"No"}</div>; react-hooks/set-state-in-effect
✖ 1 problem (1 error, 0 warnings)
eslint-plugin-react-hooks version: 6.1.1
Steps To Reproduce
eslint-plugin-react-hooks💥Link to code example: https://codesandbox.io/p/devbox/still-resonance-lzsl44?file=%2Fapp%2FComponent.tsx%3A10%2C49&workspaceId=ws_GfAuHrswXyA1DoeSwsjjjz
Widespread setState in
useEffectPatternsdidMount,isClient,isMounted,mountedReact docs 1, React docs 2, Next.js docs, next-themes docs, MUI Joy UI docs[Compiler Bug]: False positives “calling setState synchronously within an effect body” with stable primitive values #34045
I will add any more common patterns I find to the list as I encounter more examples.
Some examples of other, less widespread patterns:
URL.createObjectURL()with state Bug: react-hooks/set-state-in-effect overly strict? #34743 (comment)The current behavior
react-hooks/set-state-in-effectraises a problem with the messageCalling setState synchronously within an effect can trigger cascading rendersThe expected behavior
react-hooks/set-state-in-effectis less strict, allowing for common usage patterns while catching possible "effect loops" or other unwanted behaviorAlternatives considered
react-hooks/set-state-in-effectdocs page, showing more patterns such as the remediation patterns mentioned below that can be used in lieu of setting state directly in an effect (possible downside: some patterns may not have usable replacements outside of setting state in effects)react-hooks/set-state-in-effectdocs page, showing alternative patterns with setting state directly in an effect eg. usingstartTransition(),requestAnimationFrame()orsetTimeout()(downside: seems wrong, like a code smell or "tricking the lint rule")History
cc @jedwards1211 @josephsavona