0
0
ReactDebug / FixBeginner · 4 min read

Fix 'Hooks can only be called inside function component' in React

The error Hooks can only be called inside function component happens when you use hooks outside a React function component or custom hook. To fix it, ensure hooks like useState or useEffect are called only inside React function components or custom hooks, never in regular functions or class components.
🔍

Why This Happens

This error occurs because React hooks rely on the component's lifecycle and internal state management, which only exist inside function components or custom hooks. Calling hooks outside these contexts breaks React's rules and causes this error.

jsx
import React, { useState } from 'react';

function notAComponent() {
  const [count, setCount] = useState(0); // ❌ Hook used outside a component
  return count;
}

function App() {
  const count = notAComponent();
  return <div>{count}</div>;
}
Output
Error: Hooks can only be called inside the body of a function component.
🔧

The Fix

To fix this, move the hook call inside a valid React function component or a custom hook. Hooks must never be called in regular JavaScript functions or class components.

jsx
import React, { useState } from 'react';

function App() {
  const [count, setCount] = useState(0); // ✅ Hook inside function component

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Output
A webpage showing 'Count: 0' and a button labeled 'Increment'. Clicking the button increases the count number.
🛡️

Prevention

Always call hooks at the top level of React function components or custom hooks. Avoid calling hooks inside loops, conditions, or nested functions. Use ESLint with the eslint-plugin-react-hooks plugin to catch incorrect hook usage early.

  • Write hooks only in function components or custom hooks.
  • Keep hook calls at the top level, not inside conditions or loops.
  • Use linting tools to enforce rules automatically.
⚠️

Related Errors

Other common hook-related errors include:

  • Invalid hook call warning: Happens if React versions mismatch or multiple React copies exist.
  • Hooks called conditionally: Leads to inconsistent hook order and errors.

Fix these by ensuring consistent React versions and always calling hooks unconditionally.

Key Takeaways

Hooks must be called only inside React function components or custom hooks.
Never call hooks in regular functions, class components, or outside React components.
Always call hooks at the top level, not inside loops or conditions.
Use ESLint with react-hooks plugin to catch hook misuse early.
Ensure consistent React versions to avoid invalid hook call warnings.