Skip to content

Conditional hook call violates rules of hooks

Quick summary

You called a hook inside an if statement — React requires hooks to be called in the same order on every render.

Why this happens

  • A hook is called inside a conditional block (if/else) so it may be skipped on some renders

  • A hook is called inside a loop or dynamic function that may execute a different number of times per render

  • An early return before a hook call means the hook is skipped on some renders

Minimal example

✗ Broken code
function Profile({ user }) {
  if (!user) return <Loading />;
  const [data, setData] = useState(null); // hook after early return!
  return <div>{data}</div>;
}
✓ Fixed code
function Profile({ user }) {
  const [data, setData] = useState(null); // hook always called
  if (!user) return <Loading />;
  return <div>{data}</div>;
}

Moving the hook before the early return ensures it is called on every render, following the rules of hooks.

How to diagnose

  • Look for the React error: 'Rendered more hooks than during the previous render'

  • Check all hooks for conditional, loop, or early return placement that could change call order

  • Use the eslint-plugin-react-hooks rules-of-hooks rule to detect conditional hook calls

How to fix

  • Move the hook call to the top level of the component, before any conditionals or early returns

  • Move the condition inside the hook: useEffect(() => { if (condition) doSomething(); }) instead of if (condition) useEffect(...)

  • Split the component so the conditional renders a different component, each with its own hooks at the top level

How to prevent

  • Always call hooks at the top level of the component — never inside conditions, loops, or nested functions

  • Enable the rules-of-hooks eslint rule to catch violations at build time

Related Resources

Related Glossary

Related Lessons

← Back to language