Invalid Hook Call
The Invalid Hook Call error occurs when a React Hook (such as useState, useEffect, or useContext) is called in a place where Hooks are not allowed.
Usually happens because:
- ☑ Hook called inside if condition or loop
- ☑ Hook called inside event handler or nested helper
- ☑ Duplicate copies of React in the project
🔍 Quick Checklist:
📊 Where this usually happens (estimated occurrence)
What is Invalid Hook Call?
The Invalid Hook Call error occurs when a React Hook is called outside the body of a React function component or a custom Hook. React Hooks rely on a stable, predictable call order on every single render to map state values to their corresponding component instances. Calling Hooks conditionally, inside loops, nested functions, or event handlers violates the Rules of Hooks and causes this error. Additionally, duplicate React packages in node_modules or version mismatches between react and react-dom can also trigger this issue.
Common Causes
- Calling Hook Outside Component: Hooks cannot be called in plain JavaScript functions, event handlers, or class components.
- Calling Hook Inside Condition: Declaring Hooks inside if/else blocks changes call order dynamically based on state.
- Calling Hook Inside Loop: Placing Hooks inside for/while loops alters the count of Hook calls between renders.
- Calling Hook Inside Nested Function: Declaring Hooks inside inner functions or callbacks.
- Multiple React Versions: Having duplicate React installations in node_modules creates dispatcher conflicts.
- React and React DOM Mismatch: Out-of-sync react and react-dom dependency versions (e.g. React 19 with React DOM 18).
Common Mistakes
- Reusing Hooks inside event response methods.
- Using different package managers (like mixing npm and yarn) leading to nested node_modules copy duplicates.
How to Fix
Framework-Specific Examples
Declaring Hooks inside loops violates render order constraints.
import { useEffect } from 'react';
// Wrong
for (let i = 0; i < 3; i++) {
useEffect(() => {
console.log('Hook inside loop');
}, []);
}Server Configuration Examples
Verifying dependencies structure using npm.
npm ls react
npm ls react-dom
npm dedupeBest Practices
- Integrate the official eslint-plugin-react-hooks plugin inside your linter configs.
- Declare reusable hook logic strictly within custom Hook files prefixed with 'use' (e.g. useAuth).
Frequently Asked Questions (FAQ)
Q: Can I call Hooks inside an if statement?
No. Hooks must always be called in the same order on every render. Placing them inside conditions alters render execution order.
Q: Can I use Hooks inside loops?
No.
Q: Can class components use Hooks?
No. Hooks only work in function components and custom Hooks.
Q: Why does React care about Hook order?
React uses the order of Hook calls to associate state with the correct component instance. Changing the order breaks that mapping.