ReactEasy

What are the Rules of Hooks?

There are two rules: call hooks only at the top level of a function component or custom hook, never inside conditions, loops, nested functions or after an early return; and call hooks only from React function components or custom hooks, never from regular functions or class components. React relies on the call order being identical every render.

Rule 1: top level only

  • Not in if, for, while, switch, try/catch blocks.
  • Not after a conditional return.
  • Not inside event handlers, useMemo/useEffect callbacks or other nested functions.
  • The exception is React 19's use(...) API, which can be called conditionally.

Rule 2: only from React functions

  • Function components (capitalized) and custom hooks (use prefix).
  • Not from plain utility functions, class components or code outside React.

Why

React stores each component's hook state in a list, in call order. If a hook is skipped on one render, every later hook reads the wrong slot.

How to handle conditional logic

Call the hook unconditionally and put the condition inside it: useEffect(() => { if (!enabled) return; ... }, [enabled]). Or split into separate components and render them conditionally.

Enforcement

eslint-plugin-react-hooks (v7) provides rules-of-hooks and exhaustive-deps, plus React Compiler-powered rules (such as refs, set-state-in-render, set-state-in-effect, purity checks). Its recommended config is flat-config by default since v6. The React Compiler also refuses to optimize components that break the rules.

Also good practice

Components and hooks should be pure: same inputs, same output, no side effects during render.

Code example

tsx
1import { useEffect, useState } from "react";
2
3export function Profile({ userId }: { userId?: string }) {
4 // Wrong: hook after an early return / inside a condition
5 // if (!userId) return <p>Sign in</p>;
6 // const [user, setUser] = useState(null);
7
8 // Right: always call hooks, then branch
9 const [user, setUser] = useState<{ name: string } | null>(null);
10
11 useEffect(() => {
12 if (!userId) return; // condition INSIDE the hook
13 let ignore = false;
14 fetch(`/api/users/${userId}`)
15 .then((r) => r.json())
16 .then((u) => !ignore && setUser(u));
17 return () => {
18 ignore = true;
19 };
20 }, [userId]);
21
22 if (!userId) return <p>Sign in</p>;
23 return <p>{user ? user.name : "Loading…"}</p>;
24}
25
26// eslint.config.js (flat config)
27// import reactHooks from "eslint-plugin-react-hooks";
28// export default [reactHooks.configs.flat.recommended];

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app