Rules of Hooks
React Hooks must be called unconditionally at the top level of React components or custom Hooks. Following this rule lets React associate each Hook call with the correct state or effect across renders.
Hooks such as `useState`, `useEffect`, and `useMemo` should be called at the top level of a function component or another custom Hook. Do not put Hook calls inside `if` statements, loops, nested functions, or other conditional control flow.
The reason is that React relies on the consistent order of Hook calls between renders. If a render skips a Hook that was called previously, later Hooks can become associated with the wrong state or effect.
Hooks also should not be called from ordinary JavaScript functions. They belong in React function components or custom Hooks, where React can manage their lifecycle and ordering.
Custom Hooks may call other Hooks, but they must themselves follow the same rules. A common naming convention is to start custom Hook names with `use`, such as `useUser` or `useWindowSize`, which also helps React tooling detect Hook usage.
Key points
- Call Hooks only at the top level of React function components or custom Hooks.
- Do not call Hooks inside conditions, loops, nested functions, or callbacks.
- Keep Hook call order consistent across every render.
- Custom Hooks can use other Hooks and must follow the same rules.
- Use the `use` naming convention for custom Hooks.
Interview questions
How do you conditionally use an effect without breaking the Rules of Hooks?
Call `useEffect` unconditionally, then place the condition inside the effect callback. For example, the callback can immediately return when a required value is absent. This preserves the Hook's position while allowing its behavior to depend on state or props.
What problem do the Rules of Hooks prevent?
They preserve a stable sequence of Hook calls between renders. React can then consistently associate each Hook call with its stored state or other internal data. Conditional or otherwise unstable Hook calls can change that sequence and lead to incorrect associations. The rules therefore make Hook usage predictable for React.
Where can Hooks be called?
Hooks can be called at the top level of React function components and custom Hooks. They should not be called from ordinary JavaScript functions, class methods, loops, conditions, or nested functions. Custom Hooks can compose other Hooks while following the same restrictions.
Why can't you call a React Hook inside an `if` statement?
React expects Hooks to be called in the same order on every render. If a condition causes one Hook call to be skipped, subsequent Hook calls can shift positions. That can cause React to associate state or effects with the wrong Hook. Therefore, keep the Hook call unconditional and put the condition inside the Hook's logic when appropriate.