Skip to main content
Practice Problems

Rules for using hooks in React

Hooks are functions that allow using state and other React features in functional components.

But for React to correctly track and call hooks, you must strictly follow rules for their usage.


Main Rules for Using Hooks

Call Hooks Only at Top Level

You cannot call hooks inside conditions, loops or nested functions.

Bad:

tsx
if (someCondition) { const [count, setCount] = useState(0); // error }

Good:

tsx
const [count, setCount] = useState(0); if (someCondition) { // can use count here }

Why? React relies on hook call order at each render. If you call hook inside condition — order can be violated.

Call Hooks Only in Functional Components or Inside Custom Hooks

You cannot call hooks in regular functions, handlers, conditions outside component.

Cannot:

tsx
function doSomething() { const [val, setVal] = useState(0); // error }

Can:

tsx
function MyComponent() { const [val, setVal] = useState(0); // correct return <p>{val}</p>; }

Or inside custom hook:

tsx
function useCustomLogic() { const [state, setState] = useState(false); return { state, setState }; }

Hooks Must Be Called in Same Order at Every Render

You cannot change hook order under different conditions. This leads to incorrect value matching

tsx
// Bad if (flag) { useEffect(() => {}, []); // may break on next render }

How to Ensure Correct Usage?

  • eslint-plugin-react-hooks — it helps catch violations.
  • Don't place hooks inside if, for, switch, try/catch and any nested functions.

Important:

If you violate hook usage rules, React won't be able to properly track state, effects and other internal data. This will lead to errors and unpredictable behavior.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems