Course contentsShow
← React
Lesson 974 of 2,39625. Custom HooksFree lesson

Early Returns After Hooks Are Forbidden

Return statements before the end invalidate hook order—all hooks must run on every execution path.

Early Returns After Hooks Are Forbidden

What you'll learn: Why returning early from your component before all hooks have run breaks React's internal bookkeeping.


The Core Problem

React tracks hooks by their call order. Every time your component renders, React expects the exact same sequence of hook calls in the exact same order. When you place a return statement before all your hooks have executed, you create a situation where sometimes fewer hooks run than other times—breaking that crucial ordering guarantee.

// ❌ WRONG: Early return before all hooks
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  
  if (!userId) {
    return <div>No user selected</div>; // Early return!
  }
  
  // This hook might not run every render
  useEffect(() => {
    fetchUser(userId).then(setUser);
  }, [userId]);
  
  return <div>{user?.name}</div>;
}

When userId is falsy, React calls one hook (useState). When userId exists, React calls two hooks (useState and useEffect). React now can't match up its internal hook array correctly on subsequent renders.

// ✅ CORRECT: All hooks first, then conditional rendering
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    if (!userId) return;
    fetchUser(userId).then(setUser);
  }, [userId]);
  
  if (!userId) {
    return <div>No user selected</div>;
  }
  
  return <div>{user?.name}</div>;
}

The Mental Model

Think of hooks like a numbered checklist React follows every render: "Call #1, Call #2, Call #3..." If you sometimes skip to the end at Call #1, React loses its place.

Key Takeaway: Place all hook calls at the top level before any return statements—conditional logic goes inside hooks or after all hooks have run.