Fix: Invalid hook call in React
Exact message
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
Quick answer
This React error happens for three main reasons: 1) Hooks are called inside a regular function or condition, 2) You have multiple versions of React installed, or 3) You are calling a hook outside a component.
🛠️ Fix it right here with AI Code Explainer
Edit the traceback below if needed, then let our AI suggest a fix without leaving this page.
Why this error happens
React relies on the exact order of hook calls to maintain state. If you call a hook conditionally or inside a regular JS function, React loses track.
Example: Wrong vs Right
Wrong
function MyComponent() {
if (condition) {
const [state, setState] = useState(0); // Conditional hook!
}
return <div>Test</div>;
}Right
function MyComponent() {
const [state, setState] = useState(0); // Always at the top
if (!condition) return null;
return <div>{state}</div>;
}How to fix it (step by step)
- Check that all hooks are called at the top level of your component
- Run npm ls react to check for multiple versions of React
- Delete node_modules and package-lock.json, then run npm install
- Ensure you aren't calling a hook inside a regular utility function
Frequently asked questions
Why does React care about hook order?
React uses an array internally to store hook states. It relies on the order of execution to know which state belongs to which useState call.
How do I fix duplicate React versions?
Use npm dedupe or add a resolutions field in package.json to force a single React version.
Related Search Terms
Related JS errors
Need to fix JS code not just errors?
Use the free to paste any JS snippet and get a line-by-line explanation.
Want an AI with memory for your project?
MonsterX AI remembers your codebase across chats.