Skip to content

Invalid hook call: hooks outside function component

Quick summary

You called a hook outside a function component or inside a condition — React requires hooks to be called at the top level of a component.

Why this happens

  • You called a hook inside a regular JavaScript function that is not a React component

  • You called a hook inside a conditional, loop, or nested function, violating the rules of hooks

  • You called a hook inside a class component method, which is not supported — hooks only work in function components

Minimal example

✗ Broken code
function useUserData(userId) {
  if (userId) {
    const [data, setData] = useState(null); // conditional hook!
  }
  return data;
}
✓ Fixed code
function useUserData(userId) {
  const [data, setData] = useState(null); // always called
  useEffect(() => {
    if (userId) fetchUser(userId).then(setData);
  }, [userId]);
  return data;
}

Moving the hook call to the top level ensures it is called unconditionally on every render, following the rules of hooks.

How to diagnose

  • Check the error message for 'Invalid hook call' which indicates hooks are used outside a component

  • Verify the hook is called at the top level of a function component, not inside conditions or loops

  • Use the eslint-plugin-react-hooks rules-of-hooks rule to detect invalid hook usage

How to fix

  • Move the hook call to the top level of a function component, before any conditionals

  • Convert the class component to a function component if you need to use hooks

  • Extract the hook into a custom hook (a function starting with 'use') that is called from a component

How to prevent

  • Only call hooks at the top level of function components or custom hooks — never inside conditions or loops

  • Enable the rules-of-hooks eslint rule to catch invalid hook usage at build time

Related Resources

Related Glossary

Related Lessons

← Back to language