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
recommended
recommended-typescript
recommended-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
async
functions. - Inside
setTimeout
,setInterval
,Promise.then
, etc.
Known limitations
-
It doesn’t check
set
calls inuseLayoutEffect
cleanup functions. -
It doesn’t detect
set
calls inasync
functions are being called before or after theawait
statement.
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 theset
function ofuseState
inuseEffect
.