Course contentsShow
← React
Lesson 115 of 2,3964. Conditional Rendering in JSXFree lesson

When && is Perfect: Show/Hide Based on Boolean Flags

Use && for simple show/hide cases like `isLoggedIn && <Dashboard />` where the condition is already boolean.

When && is Perfect: Show/Hide Based on Boolean Flags

You'll learn: When the && operator shines brightest for conditional rendering—showing or hiding UI based on clean boolean flags.

The Sweet Spot for &&

After learning about the zero trap and boolean coercion, you might wonder: when should I use && without worry? The answer: when your condition is already a proper boolean.

Boolean flags like isLoggedIn, hasPermission, or isLoading are designed to be true or false. They'll never accidentally be 0 or an empty string. This makes them perfect partners for the && operator:

function Dashboard() {
  const isLoggedIn = true; // Always boolean
  const hasAdminAccess = false; // Always boolean

  return (
    <div>
      {isLoggedIn && <WelcomeMessage />}
      {hasAdminAccess && <AdminPanel />}
    </div>
  );
}

Why This Works Beautifully

When isLoggedIn is true, the && evaluates to <WelcomeMessage /> and renders it. When it's false, React renders nothing (false renders invisibly). No surprises, no accidental zeros appearing on screen.

Think of boolean flags as light switches—they're only ever ON or OFF, never "sort of on" like a dimmer switch (which would be like a number that could be zero).

When to Reach for &&

Use && confidently when:

  • Your variable name clearly signals boolean intent (is..., has..., should...)
  • The value comes from comparisons that always return booleans (===, >, includes())
  • You're toggling UI visibility based on a single, clear condition

Key Takeaway: The && operator is perfect for show/hide logic when your condition is genuinely boolean—no coercion tricks needed, just clean, readable conditional rendering.