← Back to Chapters

Short-circuit Rendering

⚛️ Short-circuit Rendering

React · Conditional Rendering

✨ Quick Overview

React lets you use JavaScript’s logical && (AND) operator for short-circuit rendering. It’s a concise way to show an element only when a condition is true.

  • condition && element → React renders the element only if the condition is truthy.
  • Commonly used for simple “show / hide” UI bits like logged-in messages or empty-state messages.
  • Avoid using it with values that can be 0 or other falsy values unless you understand the behavior.

? Key Concepts

  • Logical AND: In JavaScript, a && b returns b if a is truthy, else returns a.
  • Short-circuit: If the left side is falsy, JavaScript stops evaluating and never looks at the right side.
  • React usage: If the left side is falsy, React treats the result as “nothing to render”.
  • Truthy vs Falsy: false, 0, "", null, undefined, and NaN are falsy.
  • Best fit: Use && for simple one-way conditions. Use a ternary for “either A or B”.

? Syntax & Theory

General pattern in JSX:

  • {condition && <SomeComponent />}
  • {isLoggedIn && <p>Welcome back!</p>}
  • {items.length === 0 && <p>No items yet</p>}

If condition is:

  • truthy → React sees the element and renders it.
  • falsy → React sees false, 0, null etc., and renders nothing for that expression.

? Basic Example: Logged-in Message

In React JSX, condition && element means: “Render the element only if the condition is true.”

? View Code Example
// Show a special message only when the user is logged in
function WelcomeMessage({ isLoggedIn }) {
  return (
    <div>
      <h4>Hello Visitor!</h4>
      {isLoggedIn && <p className="text-success">Welcome back, user! ?</p>}
    </div>
  );
}

? Live Output (Conceptual)

  • isLoggedIn = true → “Hello Visitor!” + “Welcome back, user! ?” are both shown.
  • isLoggedIn = false → Only “Hello Visitor!” is shown (no extra paragraph).

? Practical Example: Notifications

Use short-circuit rendering to show or hide notification text based on the number of unread messages:

? View Code Example
// Show inbox notification only when there is at least one new message
function Notifications({ count }) {
  return (
    <div className="p-2">
      <h5>Inbox</h5>
      {count > 0 && <p className="text-info">You have {count} new messages! ✉️</p>}
    </div>
  );
}

? Output Explanation

  • count = 3 → Inbox + “You have 3 new messages! ✉️”.
  • count = 0 → Only the “Inbox” heading, no extra paragraph.

? Using Multiple && Conditions

You can chain multiple && expressions for more detailed access control or display logic:

? View Code Example
// Show admin button only when the user is both logged in and an admin
function AccessPanel({ isLoggedIn, isAdmin }) {
  return (
    <div>
      {isLoggedIn && <p>Welcome User</p>}
      {isLoggedIn && isAdmin && (
        <button className="btn btn-danger">Admin Settings</button>
      )}
    </div>
  );
}

? Output Explanation

  • isLoggedIn = false → Nothing is shown.
  • isLoggedIn = true, isAdmin = false → “Welcome User”.
  • isLoggedIn = true, isAdmin = true → “Welcome User” + “Admin Settings” button.

? Using && with Lists

Short-circuit rendering is handy for showing an “empty state” when lists have no items:

? View Code Example
// Show a 'No tasks' message when the todo list is empty
function TodoList({ todos }) {
  return (
    <div>
      <h5>My Tasks</h5>
      {todos.length === 0 && (
        <p className="text-muted">No tasks available ?</p>
      )}
      <ul>
        {todos.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

? Output Explanation

  • todos = [] → “My Tasks” + “No tasks available ?”, no list items.
  • todos = ["Buy milk", "Write code"] → “My Tasks” + the two list items; “No tasks” message is not shown.

⚠️ Be Careful with Falsy Values

JavaScript treats some values as falsy — e.g. 0, "", null, undefined, and false. If you use them on the left of &&, React will not render the element.

? View Code Example
// ⚠️ Problem: 0 is falsy, so nothing is shown when the cart is empty
function Cart({ items }) {
  return (
    <p>Total items: {items.length && items.length}</p>
  );
}

// ✅ Fix: use a ternary operator so 0 is still displayed
function CartFixed({ items }) {
  return (
    <p>Total items: {items.length > 0 ? items.length : 0}</p>
  );
}

? Output Comparison

  • Cart with 0 items → “Total items: ” (nothing after the colon).
  • CartFixed with 0 items → “Total items: 0” ✅

? Combining && with Other Logic

You can combine short-circuit rendering with other techniques (like ternaries) to keep your JSX clean and expressive:

? View Code Example
// Render different messages based on whether a user object is present
function Dashboard({ user }) {
  return (
    <div>
      <h4>Dashboard</h4>
      {user && <p>Welcome, {user.name}!</p>}
      {!user && (
        <p className="text-danger">Please log in to access your data.</p>
      )}
    </div>
  );
}

? Output Explanation

  • user = null → Only the “Please log in…” message is rendered.
  • user = {`{ name: "Sam" }`} → “Welcome, Sam!” is rendered; error message is hidden.

? Common Use Cases

  • Show “Welcome back” or “Profile” sections when a user is logged in.
  • Display badges, tooltips, or hints only when a flag is turned on.
  • Empty-state messages when arrays are empty (no tasks, no notifications, etc.).
  • Feature flags — show experimental UI only when a feature flag is enabled.

? Tips & Best Practices

  • Use && for simple, one-directional conditions (show or hide).
  • Don’t use && if you need “either A or B” — use a ternary instead.
  • Be careful when the left side can be 0; use a ternary to display numeric values safely.
  • Keep conditions short; if JSX becomes messy, move logic into helper functions or variables.
  • Try to keep one concern per expression to make your JSX easy to scan and debug.

? Try It Yourself

  1. Create a component that shows a “New Message” alert only when unreadCount > 0.
  2. Build a task list that shows “All tasks done!” when the array is empty.
  3. Make a profile card that renders “Admin Options” only if isAdmin is true.
  4. Experiment with different falsy values (like 0, "", null) on the left of && and observe the behavior.

Goal: Use JavaScript’s && operator to simplify React conditional rendering, and confidently decide when to use && versus the ternary operator.