Skip to content

useHookAtTopLevel (since v1.0.0)

Diagnostic Category: lint/correctness/useHookAtTopLevel

Sources:

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

function Component1({ a }) {
if (a == 1) {
useEffect();
}
}
correctness/useHookAtTopLevel.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://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
  
function Component1({ a }) {
if (a != 1) {
return;
}
useEffect();
}
correctness/useHookAtTopLevel.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://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
  
function Component1() {
useEffect();
}