Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
You have a conditional return before some hooks.
Why this happens
React tracks hooks by their call order on every render. If a component returns early before calling all its hooks, the number of hooks changes between renders. React canβt match hooks to their previous state, so it throws this error. This is a fundamental rule: hooks must always be called in the same order, every render.
Fix 1: Move hooks before any returns
// β Early return before hook
function Profile({ userId }) {
if (!userId) return <p>No user</p>;
const [user, setUser] = useState(null); // Error!
}
// β
All hooks first, then conditionals
function Profile({ userId }) {
const [user, setUser] = useState(null);
if (!userId) return <p>No user</p>;
}
Fix 2: Donβt put hooks in conditions
// β Conditional hook
if (showExtra) {
const [extra, setExtra] = useState(null);
}
// β
Always call the hook
const [extra, setExtra] = useState(null);
Alternative solution: Extract conditional logic into a child component
If a hook is only needed conditionally, move it to a separate component that only renders when needed:
function Profile({ userId }) {
if (!userId) return <p>No user</p>;
return <UserDetails userId={userId} />;
}
function UserDetails({ userId }) {
const [user, setUser] = useState(null);
// Hooks are safe here β component only renders when userId exists
}
Prevention
- Enable the
react-hooks/rules-of-hooksESLint rule β it catches these issues at lint time. - Structure components so all hooks are at the top, before any conditional logic.
Related: React complete guide Β· React Interview Questions Β· React: Cannot Update During Transition Fix Β· JavaScript complete guide