Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 132 ยท Hooks

The Rules of Hooks and Common Hook Errors

Understand the two rules of hooks and why call order matters, then decode the most common hook errors - conditional hooks, too many re-renders, exhaustive-deps warnings and updates during render.

Hooks feel like plain function calls, but React treats them differently. It does not look hooks up by name. It remembers them by the order in which they were called during each render. Break that order and React hands your component the wrong state, or refuses to continue and shows an error.

There are only two rules, and both follow from that one fact. This lesson explains the rules, shows precisely why they exist by watching an error happen, and then walks through the hook-related messages you will meet most often, so that you can recognise each one and fix it quickly. It assumes you know useState, useEffect and custom hooks.

The two rules

  1. Only call hooks at the top level. Do not call them inside conditions, loops, nested functions, try/catch/finally blocks, or after an early return.
  2. Only call hooks from React functions. That means function components and custom hooks (functions named use...). Not ordinary functions, event handlers, or class components.

Everything else in this lesson is a consequence of these two sentences.

JSX
function Profile({ userId }) {
  // OK: top level of a component
  const [name, setName] = useState('');

  if (!userId) {
    return <p>No user</p>;
  }

  // Not OK: this hook sits after an early return,
  // so on some renders it is skipped.
  const [age, setAge] = useState(0);
  return <p>{name} {age}</p>;
}

The first hook is fine. The second one is called on some renders and skipped on others, which is exactly the situation React cannot handle.

Why call order matters

When a component renders, React keeps a list of "slots" for that component, one per hook call. On the first render the first useState fills slot 1, the second useState fills slot 2, and so on. On every later render React walks the same list: the first hook call receives slot 1's value, the second call receives slot 2's, and so on.

Imagine this component:

JSX
function Example({ showExtra }) {
  const [a, setA] = useState('A');          // slot 1
  if (showExtra) {
    const [b, setB] = useState('B');        // slot 2 (sometimes)
  }
  const [c, setC] = useState('C');          // slot 2 or 3?
}

When showExtra is true, c is the third call and reads slot 3. When it flips to false, the useState('C') call is now the second call, so React would give it the value that belongs to b. State silently moves to the wrong variable. Rather than let that happen, React compares the number and kinds of hooks between renders, and throws an error when they differ.

Because there are no names, the only identity a hook has is its position. That is also why the rules forbid loops: a loop that runs three times today and four times tomorrow produces a different number of calls.

Seeing the error: a conditional hook

Try it. This component adds a second useState only after you tick the box. The first render is fine; the change of hook count on the next render is the failure.

A conditional hook (fails on purpose)

Tick the checkbox and look at the console panel. In the development build React first warns that it "has detected a change in the order of Hooks called by" Greeting, then throws Error: Should have a queue. You are likely calling Hooks conditionally, which is not allowed. The preview goes blank, because an uncaught render error unmounts the whole tree (an error boundary can contain the damage). Other hook mismatches produce the older message "Rendered more hooks than during the previous render" instead.

The fix is never to make the hook conditional. Call it every time and make its use conditional.

JSX
function Greeting({ wantsNickname }) {
  const [name, setName] = useState('Ada');
  const [nickname, setNickname] = useState('Countess'); // always called
  return <p>Hello, {wantsNickname ? nickname : name}</p>;
}

Hooks that must be skipped sometimes (for example an effect that should only do work in some situation) put the if inside the hook:

JSX
useEffect(() => {
  if (!isOpen) return;
  document.title = 'Dialog open';
}, [isOpen]);

Early returns and hooks

The same trap appears with early returns. Everything that has to run on every render goes above the first return.

Move hooks above the early return

Click the button a few times, untick "Enabled" and tick it again: the count is still there, because the component stayed mounted and its hooks always ran in the same order.

Hooks in the wrong place

Rule 2 trips people up in three ways.

In event handlers. A handler runs when the user clicks, not while rendering, so React has no slot list to attach the hook to.

JSX
function Bad() {
  function handleClick() {
    const [n, setN] = useState(0); // wrong: not during render
  }
  return <button onClick={handleClick}>Click</button>;
}

The fix is to call useState at the top of the component and use the setter inside the handler.

In ordinary functions. A helper named getUser that calls useContext is not a hook (no use prefix) and not a component, so linters flag it. Rename it useUser, and call it only from components or other hooks.

In class components. Hooks work only in function components. If you must keep a class component, wrap its logic in a small function component that calls the hook and passes the result down.

Reading hook errors in the console

Here are the messages you will meet most often, what each one means, and how to cure it.

"Invalid hook call"

React prints "Invalid hook call. Hooks can only be called inside of the body of a function component." It means a hook ran outside rendering. Typical causes: the hook is inside an event handler, inside a regular function you call by hand (Counter() instead of <Counter />), or inside a class. In real projects there is a fourth cause: two copies of React in node_modules, so the hook comes from a different React than the renderer. Run npm ls react to check.

Calling a component as a function (fails on purpose)

The console shows "Invalid hook call. Hooks can only be called inside of the body of a function component" with its list of possible causes, followed by a TypeError: Cannot read properties of null (reading 'useState'), because no component is rendering when Counter() runs. The correct code renders <Counter /> so React is in control of when the function runs.

"Too many re-renders"

React stops an endless loop and reports "Too many re-renders. React limits the number of renders to prevent an infinite loop." The usual cause is calling a state setter while rendering, unconditionally, so each render triggers another.

Setting state during render (fails on purpose)

The console shows Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. and the preview stays empty. A close cousin is onClick={setCount(count + 1)}: that calls the setter immediately while building the JSX. Pass a function instead, onClick={() => setCount(count + 1)}.

Setting state during render is allowed in one narrow pattern: updating a component's own state, guarded by a condition so it settles, to adjust state after a prop change. In most cases computing a value during render or using a key is better. See you might not need an effect.

"Cannot update a component while rendering a different component"

This one appears when a child calls a parent's setter (or any other component's) during its own render. React warns because rendering one component must not change another.

Updating the parent during render (fails on purpose)

The console shows the warning "Cannot update a component (Parent) while rendering a different component (Child)", so it names both components, and the page still shows "Times seen: 1". The cure is to move the notification to where side effects belong: an event handler if a user caused it, or useEffect if it must happen because something rendered. Better still, remove it by lifting state up or deriving the value.

"Maximum update depth exceeded"

This appears for loops through effects: an effect sets state, which re-renders, which changes a dependency, which re-runs the effect. A frequent trigger is an object or array created in render and used as a dependency.

JSX
useEffect(() => {
  setItems([...items, 'x']);   // changes items...
}, [items]);                    // ...which re-runs this effect

Fix it by using a functional update with fewer dependencies, doing the work in an event handler, or computing the value during render. Effect dependencies covers these patterns in detail.

The exhaustive-deps warning

The React ESLint plugin (eslint-plugin-react-hooks) ships two rules. rules-of-hooks reports the rules above as errors. exhaustive-deps is a warning: it checks that every reactive value an effect or memo uses (props, state, and variables derived from them) appears in its dependency array.

JSX
useEffect(() => {
  console.log('Searching for', query);
}, []); // warning: React Hook useEffect has a missing dependency: 'query'

An empty array means "run once", but the effect reads query, so after the first render it would keep logging the first query forever. That is a stale closure. The warning is almost always right. The correct responses, in order of preference:

  1. Add the dependency. If re-running the effect when query changes is correct, list it.
  2. Move the value inside or out. A constant that does not depend on the component belongs outside it. A value used only in the effect can be created inside it.
  3. Compute during render instead of in an effect, if the effect only transforms data.
  4. Use a functional update (setCount(c => c + 1)) to avoid depending on the state you are setting.
  5. Use useEffectEvent when you need the latest value but do not want changes to re-run the effect, see useEffectEvent.

Silencing the rule with // eslint-disable-next-line is a last resort and deserves a comment explaining why it is safe.

A stale closure from a missing dependency

Click the button within the first 600 ms and read the console. The stale effect was set up once, so it reports the count from the first render (zero) even after clicks. The fresh effect is re-created whenever count changes, so it reports the current count.

A quick troubleshooting guide

Symptom Likely cause Fix
"Rendered more hooks than during the previous render" A hook after a condition or early return Move all hooks to the top level
"Invalid hook call" Hook outside a component, a class, or two copies of React Call from a component or hook; check npm ls react
"Too many re-renders" Setter called unconditionally during render Move it into a handler or effect
"Cannot update a component while rendering a different component" Parent setter called in child render Move the call to an effect or handler
Effect runs on every render Object or function created in render used as a dependency Move it out, memoize it, or derive a primitive
State seems one step behind Reading state right after setting it Use the next value in the handler, or an effect
Effect sees old values Missing dependency Add the dependency

Habits that keep you safe

  • Turn on the React ESLint plugin from day one; both rules catch real bugs.
  • Keep hooks together at the top of the component, before any if or return.
  • Put conditions inside hooks, never around them.
  • Extract complicated hook groups into a custom hook with a clear name.
  • Read the first line of the console message carefully. React's hook messages are specific and usually name the component.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does React know which stored value belongs to which useState call?

    Hooks have no names. React matches each call to a slot by order, which is why the order must be identical on every render.
  2. 2. Which code breaks the rules of hooks?

    A hook after a conditional early return is skipped on some renders, so the call order changes. A condition inside an effect is fine.
  3. 3. What usually causes the error 'Too many re-renders'?

    A setter called during render schedules another render, which calls it again. Handlers must receive a function, not the result of calling the setter.
  4. 4. A useEffect with an empty dependency array uses the variable query. What is the problem?

    With [] the effect is set up once and captures the first query. The exhaustive-deps rule warns about this because the effect should list query.
  5. 5. Where can you safely put the condition when an effect should only do work sometimes?

    The hook call itself must always happen. Put the if inside the effect callback so the hook count never changes.

Summary

  • Two rules: call hooks only at the top level, and only from function components or custom hooks.
  • React identifies hooks by call order, so the order must be the same on every render.
  • Conditional hooks, hooks after early returns and hooks in loops or handlers all break that order.
  • Put conditions inside hooks, and put every hook above the first early return.
  • Know the messages: "Invalid hook call", "Too many re-renders", "Cannot update a component while rendering a different component" and "Maximum update depth exceeded".
  • Treat exhaustive-deps warnings as real bugs (stale closures) and fix them instead of silencing them.

Next: Context