useHookAtTopLevel
Summary
Section titled “Summary”- Rule available since:
v1.0.0 - Diagnostic Category:
lint/correctness/useHookAtTopLevel - This rule doesn’t have a fix.
- The default severity of this rule is error.
- This rule belongs to the following domains:
- Sources:
- Same as
react-hooks/rules-of-hooks
- Same as
How to configure
Section titled “How to configure”{ "linter": { "rules": { "correctness": { "useHookAtTopLevel": "error" } } }}Description
Section titled “Description”Enforce that all React hooks are being called from the Top Level component functions.
This rule should be used only in React projects.
To understand why this required see https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
Examples
Section titled “Examples”Invalid
Section titled “Invalid”function Component1({ a }) { if (a == 1) { useEffect(); }}code-block.js:3:9 lint/correctness/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://react.dev/reference/rules/rules-of-hooks
function Component1({ a }) { if (a != 1) { return; }
useEffect();}code-block.js:6:5 lint/correctness/useHookAtTopLevel ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.
4 │ }
5 │
> 6 │ useEffect();
│ ^^^^^^^^^
7 │ }
8 │
ℹ Hooks should not be called after an early return.
1 │ function Component1({ a }) {
> 2 │ if (a != 1) {
│
> 3 │ return;
│ ^^^^^^^
4 │ }
5 │
ℹ For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
ℹ See https://react.dev/reference/rules/rules-of-hooks
function notAHook() { useEffect();}code-block.js:2:5 lint/correctness/useHookAtTopLevel ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This hook is being called from within a function or method that is not a hook or component.
1 │ function notAHook() {
> 2 │ useEffect();
│ ^^^^^^^^^
3 │ }
4 │
ℹ Move the hook call into the top level of a hook or component in order to use it.
ℹ See https://react.dev/reference/rules/rules-of-hooks
function Component1() { useEffect();}test("the hook", () => { renderHook(() => useHook());});Related links
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.