Calling Hooks After Early Returns
You'll learn: Why you absolutely cannot place hook calls after an early return statement, and how this violates React's fundamental hook ordering requirement.
The Problem with Early Returns
Remember that React relies on hooks being called in the exact same order on every render. When you return early from a component, any hooks placed after that return statement might be called on some renders but not others—completely breaking the order invariant.
Consider this broken example:
function UserProfile({ userId }) {
if (!userId) {
return <div>Please log in</div>;
}
// ❌ BROKEN: This hook only runs when userId exists
const [user, setUser] = useState(null);
// ❌ BROKEN: This hook also skipped when userId is missing
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);
return <div>{user?.name}</div>;
}
What goes wrong: On first render when userId is null, React records zero hooks. But when userId becomes truthy, React suddenly sees two hooks. The hook indices are now misaligned—chaos ensues.
The Fix: All Hooks Before Any Return
Move all hooks to the top of your component, before any conditional returns:
function UserProfile({ userId }) {
// ✅ CORRECT: All hooks called first
const [user, setUser] = useState(null);
useEffect(() => {
if (userId) {
fetchUser(userId).then(setUser);
}
}, [userId]);
if (!userId) {
return <div>Please log in</div>;
}
return <div>{user?.name}</div>;
}
Now React sees the same two hooks on every render, regardless of the userId value. The conditional logic moves inside the hooks, not around them.
Key Takeaway: Hooks must always be called before any return statement—place all hook calls at the top of your component and handle conditional logic inside the hooks themselves or after all hooks have been registered.