Course contentsShow
← React
Lesson 1019 of 2,39626. Rules of Hooks Deep DiveFree lesson

The rules-of-hooks Rule

Enforces that hooks are only called at the top level and only in function components or custom hooks.

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:

  1. Call location: Are hooks inside conditionals, loops, or after early returns?
  2. Calling context: Are hooks called from regular JavaScript functions instead of components or custom hooks?
  3. Naming convention: Does the calling function start with use or 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 useState inside an if statement
  • Calling useEffect after an early return
  • 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.