useHookAtTopLevel (since v12.0.0)
Enforce that all React hooks are being called from the Top Level component functions.
To understand why this required see https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
Examples
Invalid
function Component1({ a }) {
if (a == 1) {
useEffect();
}
}
nursery/useHookAtTopLevel.js:3:9 lint/nursery/useHookAtTopLevel ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.
1 │ function Component1({ a }) {
2 │ if (a == 1) {
> 3 │ useEffect();
│ ^^^^^^^^^
4 │ }
5 │ }
ℹ For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
ℹ See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
Valid
function Component1() {
useEffect();
}