Lesson

React Conditionals

10 min reading
Free Course

React Conditionals: Controlling What Appears on Screen

React conditionals let components display different markup based on authentication status, loading state, or user permissions. Because JSX expects expressions rather than multi-line control blocks, React developers rely on early return statements, ternary operators, and logical && guards.

Three Clean Conditional Patterns

Pick the pattern that matches how many branches your component needs:

  1. Early Return: Exit the function before the main JSX when handling loading spinners or error views.
  2. Ternary Operator (? :): Switch between two alternative elements inline inside JSX.
  3. Logical AND (&&): Render an optional badge or banner only when a boolean condition is true.
export function AccountPanel({ isLoading, user, unreadMessages }) {
  if (isLoading) {
    return <p>Loading account details...</p>;
  }

  return (
    <section>
      <h2>{user ? `Hello, ${user.name}` : 'Guest Mode'}</h2>

      {unreadMessages > 0 && (
        <span className="badge">
          {unreadMessages} unread messages
        </span>
      )}
    </section>
  );
}

The Infamous 0 && <Component /> Trap

In JavaScript, 0 && <Badge /> evaluates to 0, and React renders the literal number 0 into the DOM. Always convert numeric checks into strict booleans using count > 0 && <Badge /> or Boolean(count) so empty lists never print a stray zero on screen.

Common Conditional Rendering Mistakes

  • Changing Hook Order Inside if Blocks: Never call useState or useEffect after an early return statement. Put all hooks at the very top of your component before any conditional branches.
  • Deeply Nested Ternaries: Chaining three or more ? : checks inside JSX hurts readability. Extract a helper variable or dedicated sub-component instead.

Frequently Asked Questions

Can I use if / else inside JSX?

Not directly inside { ... } braces because if is a statement, not an expression. Compute a variable with if / else above return, or use a ternary operator inline.

Does conditional rendering preserve child component state?

When a component is removed from the JSX tree, React destroys its state. If you need to keep state hidden offscreen, toggle CSS classes or visibility instead.

What happens if a component returns false, null, or undefined?

React ignores all three values and renders nothing in that slot without throwing errors.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

React Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum