Skip to content

Use Hook At Top Level

Error
small-rules/use-hook-at-top-level

Enforce that React hooks are only called at the top level of components or custom hooks, never conditionally or in nested functions

Diagnostic Messages

afterEarlyReturn
This hook is being called after an early return. Hooks must be called unconditionally and in the same order every render.
conditionalHook
This hook is being called conditionally. All hooks must be called in the exact same order in every component render.
loopHook
This hook is being called inside a loop. All hooks must be called in the exact same order in every component render.
nestedFunction
This hook is being called from a nested function. All hooks must be called unconditionally from the top-level component.
recursiveHookCall
This hook is being called recursively. Recursive calls require a condition to terminate, which violates hook rules.
tryBlockHook
This hook is being called inside a try block. Hooks must be called unconditionally at the top level.

Configuration

This rule accepts one options object after the severity.

ignoreHooksOptional

Hook names that should be ignored even when they match the hook naming pattern.

importSourcesOptional

Import sources or namespace names mapped to whether their hooks should be checked.

onlyHooksOptional

If set, only these hook names are checked.

{
"jsPlugins": [
"@pobammer-ts/small-rules"
],
"rules": {
"small-rules/use-hook-at-top-level": [
"error",
{
"ignoreHooks": [
"useEntity"
],
"importSources": {},
"onlyHooks": [
"useState"
]
}
]
}
}

Examples

Conditional hook call
function Component() {
if (condition) {
useEffect(() => {});
}
}
Top-level hook call
function Component() {
useEffect(() => {});
}