React Reference ยท Rules of React
Rules of Hooks
The two Rules of Hooks: call hooks only at the top level, and only from components or custom hooks. Why order matters and how breaking it fails.
Hooks such as useState and useEffect have no names attached to their data. React remembers a component's state by the order in which the hooks are called: the first call gets the first slot, the second call the second slot, and so on. If the order or the number of calls changed between two renders, every slot after the change would be matched with the wrong hook.
So there are two rules. First, call hooks only at the top level of your function: not inside conditions, loops, nested functions, try/catch/finally blocks or after an early return. Second, call hooks only from React function components or from custom hooks (functions whose names start with use), never from ordinary functions, class components or event handlers.
function Profile({ id }) { const [user, setUser] = useState(null); // always called useEffect(() => { /* ... */ }, [id]); // always called if (!id) { return null; // early return only AFTER all hooks } return <p>{user ? user.name : 'Loading'}</p>; }
Try it
Syntax
| Place | Hook call allowed? |
|---|---|
| Top level of a function component | Yes |
Top level of a custom hook (useSomething) |
Yes |
Inside if, for, while, switch, ternary or && |
No |
After a conditional return |
No |
Inside event handlers, setTimeout, callbacks |
No |
Inside useMemo, useEffect or other hooks' callbacks |
No |
| In a class component or a plain helper | No |
use(promise) and use(context) |
Yes, and they may be conditional (they are the one exception) |
Errors: React reports "Rendered more hooks than during the previous render" or "Rendered fewer hooks than expected" when the count changes, and "Invalid hook call" when a hook runs outside a component (also caused by two copies of React in the bundle).
Usage notes
- Branch inside, not around. Move the condition into the hook's body (
ifinsideuseEffect) or split the component in two so each has a fixed list of hooks. - Loops: to use state per item, make a child component for the item; each instance has its own hooks.
- Naming matters. Linters recognize hooks by the
useprefix. A custom hook that calls hooks must start withuse; a function that calls none should not. - Install
eslint-plugin-react-hooks. It flags both rules and missing effect dependencies; see the plugin page. - Early returns are fine once every hook above them has run.
- React Compiler requires these rules and will skip components that break them.
Related
- useState, useEffect, use, Where side effects belong
- Lessons: Rules of Hooks, Custom hooks