Rules of Hooks

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

Rules of Hooks

Hooks are JavaScript functions, but they impose two additional rules that you must strictly follow. React relies on these rules to know which state corresponds to which Hook call.

Rule 1: Only Call Hooks at the Top Level

Do not call Hooks inside loops, conditions, or nested functions.

Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the exact same order each time a component renders.

Why is this rule necessary?
React relies on the order in which Hooks are called. If a Hook is inside a conditional statement, and that condition evaluates to false on a subsequent render, the Hook is skipped. This shifts the execution order of all subsequent Hooks, causing bugs and confusing state mismatches.

// ❌ BAD: Hook inside a condition
function BadComponent({ id }) {
  if (id !== '') {
    useEffect(() => {
      // Fetch data
    });
  }
  const [name, setName] = useState('John'); // React loses track of this hook!
}

// ✅ GOOD: Hook at the top level
function GoodComponent({ id }) {
  useEffect(() => {
    if (id !== '') {
      // Fetch data
    }
  }, [id]);

  const [name, setName] = useState('John');
}

Rule 2: Only Call Hooks from React Functions

Don’t call Hooks from regular JavaScript functions.

You can only call Hooks from:

  1. React functional components.
  2. Custom Hooks (functions whose names start with use).

This rule ensures that all stateful logic in a component is clearly visible from its source code.

// ❌ BAD: Calling a hook in a regular JS function
function calculateTotal() {
  const [tax, setTax] = useState(0.2); // Error!
  return 100 * (1 + tax);
}

// ✅ GOOD: Calling a hook in a Custom Hook
function useTaxRate() {
  const [tax, setTax] = useState(0.2);
  return tax;
}

ESLint Plugin

The React team provides an ESLint plugin called eslint-plugin-react-hooks that enforces these two rules automatically. It is included by default in Create React App, Next.js, and Vite templates.

Interview Questions

Q: What are the two strict Rules of Hooks?
A:

  1. Only call Hooks at the top level: Do not call them inside loops, conditions, or nested functions.
  2. Only call Hooks from React functions: Call them from functional components or custom hooks, not regular JS functions.

Q: Why can’t you put a useState hook inside an if statement?
A: Under the hood, React doesn’t track hooks by name or ID; it tracks them purely by their call order. If a hook is hidden inside an if statement that evaluates to false during a re-render, the call order shifts. React will map the wrong state to the wrong variables, completely crashing or corrupting the component.