Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 132 ยท Components and Props

Conditional Rendering

Learn every way to render conditionally in React - if/else, early returns, ternaries, &&, null, switch on state - plus the 0 trap and hiding versus unmounting.

Real interfaces change shape. A login button turns into an avatar, a loading spinner turns into a table, an error message appears and goes away. In React there is no special "if" directive and no template language to learn: a component is a JavaScript function, so you decide what to show with ordinary JavaScript. You use if statements, the ternary operator ? : and the logical &&, and you return different JSX depending on the result.

This lesson covers each technique, when to pick which, the one famous trap (0), and the question that surprises many beginners: what happens to a component's state when it disappears from the screen. You will need props from Props; the state examples preview State with useState.

if and early returns

The most readable tool for "show something completely different" is an early return:

Early return for a loading state

Early returns keep the "happy path" at the bottom with no nesting, which is why many teams prefer them for loading, error and empty states. One rule: an early return may not skip a hook call. Hooks must run in the same order on every render, so put hooks above any early return (The Rules of Hooks).

You can also assign JSX to a variable and use it later, which helps when only a small part of the output differs:

JSX
function Item({ name, packed }) {
  let label = name;
  if (packed) {
    label = name + ' (packed)';
  }
  return <li>{label}</li>;
}

The ternary operator

Inside JSX you cannot write an if statement, because JSX holds expressions and if is a statement. The conditional operator condition ? a : b is an expression, so it fits in curly braces:

Ternary for either-or output

Use a ternary for either/or choices. Nested ternaries (a ? b : c ? d : e) get unreadable quickly; switch to if statements or a lookup object instead.

The && operator: show or nothing

When the else-branch is "nothing", use &&:

JSX
{isAdmin && <AdminMenu />}

JavaScript's && returns its left operand if that is falsy, and otherwise the right one. So false && <AdminMenu /> is false, and React renders nothing for false; true && <AdminMenu /> is the element.

What counts as "nothing"

React renders no output for null, undefined, true and false. That is why a component may return null to show nothing, and why {cond && <X />} is safe when cond is a boolean. Strings and numbers, including 0 and the empty string, are real values.

The 0 trap

Because 0 is falsy, 0 && <X /> evaluates to 0, and React dutifully prints a 0 on the page:

The 0 trap with &&

The first line renders [0]; the other two render []. The fix is to make the left side a real boolean: items.length > 0 && ... or Boolean(items.length) && .... The same trap exists for NaN. The empty string '' is harmless, because it renders nothing visible. Developers learn this one the hard way, so make > 0 a habit.

Rendering nothing with null

Return null from a component to render nothing. It is how a component says "not my turn":

A component that renders nothing

A component that returns null still counts as part of the tree, and it still runs (and still runs its hooks), it just produces no DOM output. An undefined return is also accepted in React 19, though returning null explicitly makes the intent clear.

Switching on a value

When there are several states, an if-chain, a switch statement or a lookup object is clearer than stacked ternaries. A common case is a request status:

Switching on a status

Notice that the status is one string rather than separate isLoading, isError and isSuccess booleans. One state with named values cannot be in a contradictory combination like "loading and error at once". Choosing a State Structure develops that idea.

Toggling attributes and classes

Conditional rendering is not only about whole elements. You can condition a prop or a style the same way:

JSX
<button type="button" disabled={isSaving} aria-busy={isSaving}>
  {isSaving ? 'Saving...' : 'Save'}
</button>
<li className={done ? 'done' : undefined}>...</li>

For className prefer undefined over an empty or "false" string; passing undefined leaves the attribute out entirely.

Hiding versus unmounting

Here is the part that matters for correctness. When a condition becomes false and the element disappears from the returned tree, React unmounts the component: its state is destroyed. When the condition turns true again, React mounts a fresh instance with the initial state. Compare with merely hiding it using CSS, which keeps the component mounted and its state intact.

Unmounting loses state, hiding keeps it

Click each counter a few times, hide both and show them again. The "Removed" counter is back at 0; the "Hidden" counter remembers its count. Neither is wrong, they serve different goals:

  • Unmount (conditional render) when the content is not needed and you want to free resources, reset its state, or stop its effects (timers, subscriptions) while it is gone. This is the default and almost always correct.
  • Hide with CSS when re-creating it is expensive or the state must survive, for example a tab panel with a half-filled form. Be aware that hidden content is still in the DOM, still runs effects and may still be reachable by assistive technology unless you use hidden or display: none.

React 19.2 also ships an Activity component for hiding with state preserved while pausing effects; see Animation and Transitions.

Position decides identity

React matches components by type and position in the tree. If a ternary returns the same component type in the same spot in both branches, React updates the existing instance instead of replacing it, and its state carries over:

Same position, same type: state is kept

Type something in both inputs, then press the button. The first note keeps your text (the label changes to "Lin's note:" but the text is still there), because it is one Note at the same position being updated. The second resets, because the different key makes React treat them as different components. If you want a clean slate when the identity changes, give the component a key. This is the foundation of Reconciliation and Keys in Depth.

Choosing a technique

Situation Use
Whole component differs (loading, error) Early return
Either A or B inline Ternary ? :
A or nothing inline && with a real boolean
Many named states switch, lookup object
Hide but keep state CSS, or Activity
Reset state when identity changes key

Avoid deeply nested conditions inside JSX. If the markup is hard to read, extract a small component or compute the pieces into variables above the return.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does <p>{count && <b>items</b>}</p> render when count is 0?

    0 is falsy, so 0 && ... evaluates to 0, and React renders the number 0. Use count > 0 && ... instead.
  2. 2. Which values does React render as nothing?

    null, undefined, true and false produce no output. 0 and NaN are rendered as text; the empty string renders nothing visible.
  3. 3. Why can't you write an if statement directly inside JSX curly braces?

    JSX interpolation accepts JavaScript expressions only. Use ?:, && or decide before the return statement.
  4. 4. A counter component is rendered with {show && <Counter />}. The user increments it, hides it and shows it again. What count do they see?

    Removing the element unmounts the component and destroys its state. Showing it again creates a new instance with initial state.
  5. 5. Where must hooks be placed relative to an early return in a component?

    Skipping a hook on some renders breaks the rule that hooks are called in the same order every time. Call them above any conditional return.

Summary

  • Conditional rendering is plain JavaScript: if/early return, ? :, &&, switch, lookup objects.
  • null, undefined, true and false render nothing; 0 and NaN render text, so write count > 0 && ....
  • A component may return null to render nothing; it is still part of the tree.
  • Prefer one status value over several booleans that can contradict each other.
  • Removing an element unmounts it and destroys state; hiding with CSS keeps state.
  • React identifies components by type and position; use key to force a reset.

Next: Rendering Lists and Keys