Skip to content
Back to Pathway
hooksintermediate

Rules of Hooks

Hooks must only be called at the top level of React function components or custom hooks.

Mental Model

"The Assembly Line: Every car on the conveyor belt must receive parts in the exact sequential order without skipping stations."

Interactive Engine Walkthrough

Fiber Hooks Linked List
useState
"Initial"
useEffect
"Idle"

Invariant:The stability of this sequence is what allows React to persist state across asynchronous render cycles.

Reference Code Snippet

Component.jsx
JSX / React 19
1// ❌ ERROR: Hook inside condition
2if (loggedIn) {
3  useEffect(() => { ... });
4}
5
6// ✅ CORRECT: Condition inside hook
7useEffect(() => {
8  if (loggedIn) { ... }
9}, [loggedIn]);
Technical Takeaways & Best Practices
  • 01.Rule 1: Only call hooks at the top level (never in if statements, for loops, or nested functions).
  • 02.Rule 2: Only call hooks from React function components or custom hooks.
  • 03.Enforced by the eslint-plugin-react-hooks linter plugin.

01. Fixed Call Order

React relies on the **order** in which Hooks are called. Internally, it treats hooks as a linked-list. If you skip a hook because of an `if` statement, the pointers for every subsequent hook will shift, returning the wrong state to the wrong variables.

Internal Pointer Fail

Hook A
MISSING
Hook C (Shifted)

02. Only Call in React

Hooks can only be called from **React function components** or **Custom hooks**. They cannot be called from regular JavaScript functions. This is because hooks require access to the "dispatcher" of the currently rendering component instance.

Maintainability Note

"Use the 'eslint-plugin-react-hooks' tool in your IDE. It will automatically catch violations of these rules before you ever run your code. In the Cosmos, laws are enforced by linting."