Invalid hook call. Hooks can only be called inside the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
This error means youβre calling a React hook (useState, useEffect, etc.) somewhere React doesnβt allow it. There are exactly three causes.
Cause 1: Calling Hooks Outside a Component
Hooks can only be called inside function components or custom hooks. Not in regular functions, not in class components.
// β Hook in a regular function
function getUser() {
const [user, setUser] = useState(null); // π₯
return user;
}
// β
Hook in a component
function UserProfile() {
const [user, setUser] = useState(null);
return <div>{user?.name}</div>;
}
// β
Hook in a custom hook
function useUser() {
const [user, setUser] = useState(null);
return user;
}
Also check: are you calling a hook inside a class component?
// β Hooks don't work in class components
class MyComponent extends React.Component {
render() {
const [count, setCount] = useState(0); // π₯
}
}
Convert to a function component or use this.state instead.
Cause 2: Breaking the Rules of Hooks
Hooks must be called at the top level β not inside conditions, loops, or nested functions.
// β Hook inside a condition
function MyComponent({ isLoggedIn }) {
if (isLoggedIn) {
const [user, setUser] = useState(null); // π₯
}
}
// β
Move the hook to the top level
function MyComponent({ isLoggedIn }) {
const [user, setUser] = useState(null);
if (!isLoggedIn) return <Login />;
return <Dashboard user={user} />;
}
// β Hook inside a loop
items.forEach(() => {
const [val, setVal] = useState(null); // π₯
});
Cause 3: Multiple Copies of React
This is the sneakiest cause. Your project has two different copies of React loaded.
Diagnose it:
npm ls react
If you see two versions, thatβs the problem.
Common causes:
- A linked package (
npm link) has its ownnode_modules/react - A dependency bundles its own React
Fix:
# Remove duplicate
rm -rf node_modules && npm install
# If using npm link, add react as a peer dependency
# in the linked package, not a regular dependency
# Force a single React version
# In package.json:
{
"overrides": {
"react": "$react"
}
}
Webpack/Vite alias fix:
// vite.config.js
resolve: {
alias: {
react: path.resolve('./node_modules/react')
}
}
Quick Checklist
- β Is the hook inside a function component (not a class or regular function)?
- β Is the hook at the top level (not inside if/for/callback)?
- β
Does
npm ls reactshow only one version? - β
Is your component name capitalized? (
UserProfile, notuserProfile)