The rules-of-hooks Rule
What you'll learn: How ESLint's rules-of-hooks rule automatically catches violations of React's hook calling requirements.
What This Rule Does
The rules-of-hooks rule is part of eslint-plugin-react-hooks and enforces the two cardinal rules you've learned: hooks must be called at the top level (no conditionals, loops, or nested functions) and only inside React function components or custom hooks.
This rule acts as your safety net, catching violations before they cause runtime bugs.
How It Works
The linter analyzes your code statically, checking:
- Call location: Are hooks inside conditionals, loops, or after early returns?
- Calling context: Are hooks called from regular JavaScript functions instead of components or custom hooks?
- Naming convention: Does the calling function start with
useor is it a PascalCase component?
When it finds a violation, you get an immediate error message in your editor—no need to run the app and encounter cryptic bugs.
Why This Matters
Remember the index-based hook registry? If you conditionally call a hook, React's internal tracking breaks. The rules-of-hooks rule prevents you from shipping code with these timing bombs. It catches mistakes like:
- Putting
useStateinside anifstatement - Calling
useEffectafter an earlyreturn - Using hooks inside event handlers
- Calling hooks from utility functions that don't start with
use
Think of it as a spell-checker for hook usage—it won't let you save code that violates the fundamental invariants React depends on.
Key Takeaway: The rules-of-hooks ESLint rule automatically enforces that hooks are only called at the top level of function components or custom hooks, catching violations instantly during development.