Rules
no-direct-set-state-in-use-layout-effect
Full Name in eslint-plugin-react-hooks-extra
Full Name in @eslint-react/eslint-plugin
Features
🧪
Presets
recommendedrecommended-typescriptrecommended-type-checked
Description
Disallow direct calls to the set function of useState in useLayoutEffect.
Directly setting state in useLayoutEffect can lead to:
- Redundant state: You might be duplicating derived values that could be computed during render.
- Unnecessary effects: Triggering re-renders that could be avoided.
- Confusing logic: It can make component behavior harder to reason about.
What counts as a violation?
This is not allowed:
Instead, compute the value during render:
What is allowed?
The rule does not flag indirect calls, such as:
- Inside event handlers.
- Inside
asyncfunctions. - Inside
setTimeout,setInterval,Promise.then, etc.
Known limitations
-
It doesn’t check
setcalls inuseLayoutEffectcleanup functions. -
It doesn’t detect
setcalls inasyncfunctions are being called before or after theawaitstatement.
Examples
The first three cases are common valid use cases because they are not called the set function directly in useLayoutEffect:
Passing
Passing
Passing
The following examples are derived from the React documentation:
Failing
Passing
Failing
Passing
Failing
Passing
Failing
Passing
Implementation
Further Reading
See Also
no-direct-set-state-in-use-effect
Disallow direct calls to thesetfunction ofuseStateinuseEffect.