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 Simulation
Invariant:The stability of this sequence is what allows React to persist state across asynchronous render cycles.
Executable Code Snippet
1// ❌ ERROR: Hook inside condition
2if (loggedIn) {
3 useEffect(() => { ... });
4}
5
6// ✅ CORRECT: Condition inside hook
7useEffect(() => {
8 if (loggedIn) { ... }
9}, [loggedIn]);- 01.Component re-renders are triggered by state or prop changes.
- 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
- 03.Automatic batching optimizes multiple state updates into a single render cycle.
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
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."