Rules of React Hooks
Rules of React Hooks
1. What Are React Hooks?
Introduced in React 16.8, Hooks are functions that let you "hook into" React state and lifecycle features from functional components. Examples include useState, useEffect, useContext, useRef, and useMemo.
Because React relies on the internal execution order of functions to track hook state behind the scenes, you must adhere strictly to The Two Rules of Hooks.
2. Rule 1: Only Call Hooks at the Top Level
Do NOT call Hooks inside loops, conditions, nested functions, or try/catch blocks.
Always call Hooks at the very top level of your React function, before any early returns:
Why does this rule exist?
React does not track hooks by name or ID. Instead, React maintains an internal array / linked list of hook cells for each component instance. On every render, React matches each hook call with the next cell in the list. If a hook is skipped inside an if block, every subsequent hook shifts out of position, permanently corrupting the component's state!
3. Rule 2: Only Call Hooks from React Functions
Do NOT call Hooks from regular JavaScript functions.
You must only call Hooks from:
- 1React Functional Components: Functions that return JSX and start with an uppercase letter.
- 2Custom Hooks: Functions whose names start with
use(e.g.,useFetch,useAuth,useLocalStorage).
4. The ESLint Plugin for Hooks
React provides an official ESLint plugin: eslint-plugin-react-hooks.
It includes two essential linting rules:
react-hooks/rules-of-hooks: Enforces the two core rules automatically in your IDE and build step.react-hooks/exhaustive-deps: Verifies that all reactive dependencies are included inuseEffectanduseCallbackdependency arrays.
Practice Quiz
useState hook after an early if (error) return null;?The useEffect Hook for Side Effects
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Managing Loading, Error, and Empty States | The useEffect Hook for Side Effects |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.