πŸ”§ Error Fixes
Β· 1 min read

React: Rendered Fewer Hooks Than Expected β€” How to Fix It


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-hooks ESLint 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

πŸ“˜