Sub topic 1
The Rules of Hooks you must keep
Every custom hook you write is built from the built-in hooks, so it inherits their constraints. If you break these constraints, React does not always raise an error. The component can quietly read the wrong state. This chapter explains the two rules, the mechanism that makes them necessary, and the patterns that keep your code inside them.
Prerequisites
This chapter assumes you can already:
- Write function components with JSX and pass props.
- Use
useStateanduseEffectin a component. - Read modern JavaScript: arrow functions, destructuring, closures.
You do not need to have written a custom hook yet. That starts in the next chapter.
The two rules
React documents two rules.
- Only call hooks at the top level. Do not call them inside conditions, loops, nested functions, or after an early
return. - Only call hooks from React functions. That means function components and other custom hooks. Do not call them from regular JavaScript functions, class components, or event handlers.
The first rule is the one that causes most bugs. "Top level" means the top level of the function body, before any return that might skip a hook.
Why order matters
A function component has no name for each hook call. You write useState(0) and React gives you back a value, but nothing in your code says which piece of state you mean. React identifies each hook by its position in the sequence of calls during a render.
Conceptually, React keeps a list of slots for each component. On the first render, the first hook call fills slot 1, the second fills slot 2, and so on. On every later render, React walks the same list in the same order and hands each call the value stored in its slot.
This only works if every render makes the same hook calls in the same order.
A concrete failure
Here is a component that breaks the first rule.
import { useState, useEffect } from 'react';
function Profile({ userId }) {
if (!userId) {
return null; // early return BEFORE the hooks below
}
const [name, setName] = useState('');
useEffect(() => {
document.title = name;
}, [name]);
return <input value={name} onChange={(e) => setName(e.target.value)} />;
}When userId is truthy, the component calls two hooks. When userId is empty, it calls none. If the prop changes between renders, React sees a different number of hooks than it recorded. In development, React logs a warning such as "Rendered fewer hooks than expected" or "React has detected a change in the order of Hooks". It can also throw an error, depending on how the sequence changed.
The failure is worse when the count stays the same but the order changes. Then React has no way to detect the problem. For example, suppose a condition decides between useState and useRef at the same position. React hands the wrong slot value to the wrong call, and your component shows the wrong data.
The fix: hooks first, decisions after
Move every hook above the early return.
import { useState, useEffect } from 'react';
function Profile({ userId }) {
const [name, setName] = useState('');
useEffect(() => {
if (!userId) return; // condition goes INSIDE the effect
document.title = name;
}, [userId, name]);
if (!userId) {
return null; // safe: all hooks have already run
}
return <input value={name} onChange={(e) => setName(e.target.value)} />;
}The hooks now run on every render. The decision about whether to do work moves inside the effect, or into the JSX that follows.
Common ways to break rule one
Each of the following is a violation, even if it appears to work in a quick test.
| Pattern | Why it breaks | What to do instead |
|---|---|---|
| `if (x) { useState(0); }` | The call runs only on some renders | Call the hook always, branch on its result |
| `for (...) { useEffect(...); }` | The number of calls depends on the data | Use one hook that handles a list |
| `items.map(() => useState(0))` | The call count follows the array length | Extract a child component per item |
| `return` before a hook | Later hooks are skipped on that render | Put all hooks above the `return` |
| `function onClick() { useRef(); }` | Event handlers run outside rendering | Call the hook at top level, use its value in the handler |
| `cond && useCustomHook()` | Short-circuiting skips the call | Call it unconditionally and pass `cond` as an argument |
| `try { useX(); } catch {}` | Control flow can skip later hooks | Handle errors inside the hook |
Loops and lists
The loop case is the one people find hardest to work around. If each list item needs its own state, give each item its own component.
import { useState } from 'react';
function Row({ label }) {
const [checked, setChecked] = useState(false); // top level of Row
return (
<label>
<input
type="checkbox"
checked={checked}
onChange={() => setChecked((value) => !value)}
/>
{label}
</label>
);
}
function List({ items }) {
return items.map((item) => <Row key={item.id} label={item.label} />);
}Each Row has a fixed hook sequence. List has no hooks, so its varying length does not matter.
Conditional behavior without conditional calls
If you want a hook to do something only sometimes, give it an argument that turns the behavior on or off. The call stays unconditional.
import { useEffect } from 'react';
function useDocumentTitle(title, enabled) {
useEffect(() => {
if (!enabled) return;
const previous = document.title;
document.title = title;
return () => {
document.title = previous;
};
}, [title, enabled]);
}The caller writes useDocumentTitle('Inbox', isActive) and never wraps the call in an if.
Rule two: where hooks may be called
Hooks need to run during React's rendering of a component, because that is when React knows which component's slot list to use. That gives the following allowed and disallowed locations.
- Allowed: the body of a function component.
- Allowed: the body of a custom hook, which is a function whose name starts with
use. - Not allowed: class components. Use a function component instead.
- Not allowed: event handlers, timers, and promise callbacks. They run after rendering, outside any component's slot list.
- Not allowed: functions you pass to
useMemo,useReducer, oruseStateas initializers. React runs those during render, but they are not components or hooks.
If an event handler needs something a hook provides, call the hook at the top of the component and use the returned value inside the handler.
Custom hooks and the `use` prefix
A custom hook is an ordinary function that calls other hooks. The use prefix is a naming convention, but it carries real weight. Two tools depend on it.
- The linter. The
react-hooksESLint plugin treats any function nameduseSomethingas a hook. It enforces rule one inside it, and it enforces rule two at every call site. It cannot do that for a function namedgetSomething. - Readers.
usetells another developer that this function must be called at the top level, and that it may hold state.
Naming a function useFormat when it calls no hooks is misleading. It makes the linter apply hook restrictions to code that does not need them, so callers cannot use it inside a loop or callback. If a function calls no hooks, give it a plain name.
The rules are transitive. If useDebouncedValue calls useState and useEffect, then every caller of useDebouncedValue must also follow the rules, because its hook sequence becomes part of theirs.
Enforcing the rules with the linter
Do not rely on remembering the rules. Install the plugin and turn the rules on.
// eslint.config.js (flat config)
import reactHooks from 'eslint-plugin-react-hooks';
export default [
{
plugins: { 'react-hooks': reactHooks },
rules: {
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
},
},
];rules-of-hooks reports both rules. exhaustive-deps checks dependency arrays, which a later chapter covers. The linter catches most violations before the code runs. It can still miss patterns it cannot analyze statically, such as hooks called through a function stored in a variable.
The one exception: `use`
React 19 added an API named use, which reads a promise or a context. Unlike the hooks above, you may call it inside conditions and loops. It still must be called from a component or a hook, and it cannot be called inside a try/catch block. This chapter's rules apply to every other hook, including all the built-in useX hooks and your own custom hooks.
Summary of habits
- Put hooks at the top of the function, then make decisions.
- Put conditions inside hooks and effects, not around them.
- Use child components when each item in a list needs state.
- Name a function
use...only if it calls hooks. - Keep
react-hooks/rules-of-hooksset toerror.
Exercise
This component sometimes throws "Rendered more hooks than during the previous render". Why, and how do you fix it? function Greeting({ user }) { if (!user) return <p>Loading</p>; const [draft, setDraft] = useState(user.name); return <input value={draft} onChange={(e) => setDraft(e.target.value)} />; }
Show answer
When user is falsy, the component returns before reaching useState, so it calls zero hooks. When user arrives, it calls one. React sees the count change between renders. Fix it by calling useState first, before the early return, for example const [draft, setDraft] = useState(user?.name ?? '');. Then render the loading message afterward. If the draft should reset when user changes, split the form into a child component that receives user as a prop, and render it only when user exists.
Exercise
A teammate writes function useFormatPrice(value) { return '$' + value.toFixed(2); } and then cannot call it inside a .map() callback because the linter complains. What should change?
Show answer
The function calls no hooks, so it should not have the use prefix. Rename it to formatPrice. The linter then treats it as a normal function, and it can be called anywhere, including inside loops and callbacks.