Fix 'Hooks can only be called inside function component' in React
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.
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>; }
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.
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> ); }
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.