Skip to content

Lesson 5 of 37Thinking in React

Conditional Rendering

Show different UI for different data with early returns, ternaries, && and null, and avoid the stray 0 bug.

22 min read0/8 questions

Real screens are full of "it depends": show a spinner while loading, an error if the request failed, an empty state if there is no data, a badge only when there are unread messages. In React there is no special template syntax for this. You use plain JavaScript, and picking the right tool for each case keeps components readable.

Early return with if

When a whole component looks different depending on a condition, use a normal if and return early. This is the clearest option when the branches are big.

React
type Status = "loading" | "error" | "ready"; function Inbox({ status, count }: { status: Status; count: number }) { if (status === "loading") return <p>Loading messages...</p>; if (status === "error") return <p style={{ color: "crimson" }}>Could not load messages.</p>; return <h3>You have {count} messages</h3>;} export default function App() { return ( <div> <Inbox status="loading" count={0} /> <Inbox status="error" count={0} /> <Inbox status="ready" count={12} /> </div> );}

if is a statement, so it cannot go inside JSX braces. It goes before the return. Each early return handles one case and the "happy path" sits at the bottom.

The same component can produce a different tree on each render. React compares trees and adds or removes elements to match whichever branch ran.

Which branch is in the tree?
InboxSpinnerstatus === "loading"ErrorMessagestatus === "error"Badgeonly when unread > 0MessageListstatus === "ready"root

While loading, the early return renders only the spinner. Nothing else exists in the DOM.

1/4

Rendering nothing with null

A component can return null to render nothing at all. This is how you hide a whole component based on its props.

function Banner({ message }: { message?: string }) {
  if (!message) return null;
  return <div className="banner">{message}</div>;
}

Returning null is not an error and does not unmount the parent. It just means "nothing here this time".

Quick check
Why does <div>{if (ok) { <p>Yes</p> }}</div> fail to compile?
Need a nudge? A hint rules out a wrong answer.

Ternary: this or that

Inside JSX, the ternary condition ? a : b picks between two pieces of UI. It is an expression, so it fits in braces.

React
const users = [ { id: 1, name: "Ada", online: true, admin: true }, { id: 2, name: "Sam", online: false, admin: false },]; export default function App() { return ( <ul> {users.map((u) => ( <li key={u.id}> {u.name}: {u.online ? <strong>online</strong> : <span style={{ color: "#888" }}>away</span>} {u.admin ? " (admin)" : null} </li> ))} </ul> );}

Ternaries get hard to read when nested (a ? b : c ? d : e). When you have three or more cases, move the logic into a variable or a small component with early returns.

&& and the 0 pitfall

For "show this or nothing", condition && <Thing /> is the common shortcut. It works because && returns the right side when the left is truthy, and the left side when it is falsy. React renders false, null and undefined as nothing.

The trap: 0 is falsy but React renders it. So count && <Badge /> with count = 0 puts a stray 0 on the screen. Run this and look at the second line.

React
export default function App() { const unread = 0; return ( <div> <p>Correct: {unread > 0 && <span>({unread} new)</span>}</p> <p>Buggy: {unread && <span>({unread} new)</span>}</p> </div> );}
Predict the outputJavaScript

What text does this render?

const items = [];
<p>Cart {items.length && <b>{items.length} items</b>}</p>
Need a nudge? Hints walk you through it.

The fix is always to make the left side a boolean: count > 0 &&, !!count &&, or Boolean(count) &&.

Quick checkPick all that apply
Which of these never show a stray 0 when n is 0? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

Conditional classes and attributes

Most conditions in real code do not swap whole elements. They change a class, an aria- attribute, or whether a button is disabled. That is still plain JavaScript inside braces, with a few rules worth knowing.

React
import { useState } from "react"; function cx(...parts: (string | false | null | undefined)[]) { return parts.filter(Boolean).join(" ");} const PAGES = ["Home", "Pricing", "Docs"]; export default function App() { const [page, setPage] = useState("Home"); const [compact, setCompact] = useState(false); return ( <div> <style>{` .nav { display: flex; gap: 4px; } .link { padding: 6px 10px; border: 1px solid #ccc; background: none; } .link.active { background: #191919; color: #fff; } .nav.compact .link { padding: 2px 6px; font-size: 13px; } `}</style> <nav className={cx("nav", compact && "compact")}> {PAGES.map((p) => ( <button key={p} className={cx("link", p === page && "active")} aria-current={p === page ? "page" : undefined} disabled={p === "Docs" && compact} onClick={() => setPage(p)} > {p} </button> ))} </nav> <label style={{ display: "block", marginTop: 8 }}> <input type="checkbox" checked={compact} onChange={(e) => setCompact(e.target.checked)} /> Compact (disables Docs) </label> </div> );}

cx is a tiny version of the popular clsx package: it drops every falsy part and joins the rest. A hand-written template literal like `link ${active ? "active" : ""}` works too, but it is easy to end up with "link undefined" or stray spaces. In Tailwind projects you will usually see a cn() helper that combines clsx with tailwind-merge, so a later p-2 correctly beats an earlier p-4. The styling lesson covers that.

How React writes attribute values:

  • undefined or null removes the attribute. That is why aria-current={isActive ? "page" : undefined} only appears on the active link.
  • Boolean HTML attributes such as disabled, hidden, checked and required are left out when false and written when true.
  • aria-* and data-* attributes turn booleans into strings. aria-expanded={false} writes aria-expanded="false", which is exactly what screen readers want. But data-open={false} writes data-open="false", and a CSS selector [data-open] still matches it, because the attribute exists. Pass undefined when you mean "not there".

To add a whole group of props only sometimes, spread a conditional object: <a {...(isExternal ? { target: "_blank", rel: "noreferrer" } : {})}>. When the condition changes the element itself, pick the tag first: const Tag = href ? "a" : "button", then render <Tag>.

Quick check
Your CSS has [data-open] .menu { display: block; } and you render <div data-open={isOpen}>. What happens when isOpen is false?
Need a nudge? A hint rules out a wrong answer.

Switching views with state

Conditions often depend on something the user did: which tab is selected, whether a panel is open. That needs a value the component remembers between renders. You met useState in the lists lesson; here it holds which view is active, and clicking a button changes it. React re-renders, and your conditions pick the new view.

React
import { useState } from "react"; type View = "list" | "grid" | "map"; export default function App() { const [view, setView] = useState<View>("list"); return ( <div> <div style={{ display: "flex", gap: 6, marginBottom: 8 }}> {(["list", "grid", "map"] as View[]).map((v) => ( <button key={v} onClick={() => setView(v)} style={{ fontWeight: v === view ? 700 : 400 }}> {v} </button> ))} </div> {view === "list" && <p>Showing results as a list.</p>} {view === "grid" && <p>Showing results as a grid of cards.</p>} {view === "map" && <p>Showing results on a map.</p>} </div> );}

For many views, a lookup object is tidier than a chain of &&:

const views: Record<View, ReactNode> = {
  list: <ListView />,
  grid: <GridView />,
  map: <MapView />,
};
return <div>{views[view]}</div>;
Match the pairs0/4 matched

Pick the clearest tool for each situation.

Choose an item, then its match on the other side.

Same position, same type: when state survives a switch

Conditional rendering has a side effect that surprises people. When you switch between two branches, the components inside either keep their state or lose it, and which one happens depends on something you might not think about: where the component sits in the tree.

React does not know which variable or which branch of your code produced an element. It only sees the tree that comes out. For each spot in that tree it asks two questions: is it the same type of component, at the same position among its siblings? If yes, React keeps the existing component and its state and just gives it new props. If no, it unmounts the old one (state gone) and mounts a new one.

Try both scoreboards. Add some points for Ada, then switch players.

React
import { useState } from "react"; function Counter({ name }: { name: string }) { const [score, setScore] = useState(0); return ( <p> {name}: {score} <button onClick={() => setScore(score + 1)}>+1</button> </p> );} function TernaryBoard() { const [isAda, setIsAda] = useState(true); return ( <section> <strong>Ternary</strong> {isAda ? <Counter name="Ada" /> : <Counter name="Sam" />} <button onClick={() => setIsAda(!isAda)}>Switch player</button> </section> );} function SeparateBoard() { const [isAda, setIsAda] = useState(true); return ( <section> <strong>Two && conditions</strong> {isAda && <Counter name="Ada" />} {!isAda && <Counter name="Sam" />} <button onClick={() => setIsAda(!isAda)}>Switch player</button> </section> );} export default function App() { return ( <div style={{ display: "grid", gap: 16 }}> <TernaryBoard /> <SeparateBoard /> </div> );}

In the ternary board, Sam inherits Ada's score. Both branches put a Counter in the same slot, so React sees one Counter whose name prop changed. In the second board, each && expression is its own slot. When Ada is showing, slot two holds false; when you switch, slot one becomes false and slot two gets a Counter. Different positions, so Ada's counter is destroyed and Sam's starts at zero.

What React sees in each board
AppCounterslot 1: Ada or SamswitchTernaryBoardAdaSlotslot 1: Counter or falseSamSlotslot 2: Counter or falsetoggleSeparateBoardroot

Ternary: one slot, and it always holds a Counter. Switching only changes the name prop, so the score survives.

1/3

The same rule explains several other bugs and tricks:

  • Wrapping one branch in a different element (<div> in one, <section> in the other) resets everything inside it, because the parent's type changed.
  • A component defined inside another component is a new function, so a new type, on every render. Its state resets each time.
  • A key makes two components at the same position different. {isAda ? <Counter key="ada" name="Ada" /> : <Counter key="sam" name="Sam" />} gives each player their own fresh counter. That is the key reset from the components lesson.

This is a real source of production bugs: a form that shows "Email" or "Username" fields depending on a toggle, where the text typed into one quietly moves into the other.

Predict the outputJavaScript

The user types ada@x.io into the Email field, then ticks a box that sets byUsername to true. What does the Username field contain?

function Field({ label }) {
const [text, setText] = useState("");
return <input aria-label={label} value={text}
  onChange={(e) => setText(e.target.value)} />;
}

{byUsername ? <Field label="Username" /> : <Field label="Email" />}
Need a nudge? Hints walk you through it.

Loading, empty, error and success as one union

The Inbox at the top of this lesson took a single status prop. In real code, data-loading components often grow three separate pieces of state instead:

const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [orders, setOrders] = useState<Order[] | null>(null);

Three independent values allow eight combinations, and most are nonsense: loading and failed, failed and holding data. Each nonsense combination is a bug waiting for one forgotten setError(null). The classic one: a request fails, the user retries, the retry succeeds, and the screen shows the fresh orders and the old error message.

Model the states that can actually exist as a discriminated union instead. Each status carries only the data that makes sense for it:

type Remote<T> =
  | { status: "loading" }
  | { status: "error"; message: string }
  | { status: "success"; data: T };

Now "error with data" cannot be written down, and switching status replaces everything in one update. Notice there is no "empty" status. From the server's point of view an empty list is a success, so "empty" is a rendering decision, made after you know you have data. Run this and try each outcome.

React
import { useState } from "react"; type Order = { id: number; item: string };type Remote<T> = { status: "idle" } | { status: "loading" } | { status: "error"; message: string } | { status: "success"; data: T }; function fakeFetch(outcome: "orders" | "none" | "fail"): Promise<Order[]> { return new Promise((resolve, reject) => setTimeout(() => { if (outcome === "fail") reject(new Error("Server returned 503")); else resolve(outcome === "none" ? [] : [{ id: 1, item: "Keyboard" }, { id: 2, item: "Monitor" }]); }, 600), );} function Orders({ state }: { state: Remote<Order[]> }) { switch (state.status) { case "idle": return <p>Pick an outcome to load orders.</p>; case "loading": return <p>Loading orders...</p>; case "error": return <p role="alert" style={{ color: "crimson" }}>Could not load orders: {state.message}</p>; case "success": if (state.data.length === 0) return <p>No orders yet. Your first order will show up here.</p>; return ( <ul> {state.data.map((o) => <li key={o.id}>{o.item}</li>)} </ul> ); }} export default function App() { const [state, setState] = useState<Remote<Order[]>>({ status: "idle" }); async function load(outcome: "orders" | "none" | "fail") { setState({ status: "loading" }); try { setState({ status: "success", data: await fakeFetch(outcome) }); } catch (e) { setState({ status: "error", message: (e as Error).message }); } } return ( <div> <div style={{ display: "flex", gap: 6, marginBottom: 8 }}> <button onClick={() => load("orders")}>Load orders</button> <button onClick={() => load("none")}>Load empty</button> <button onClick={() => load("fail")}>Load and fail</button> </div> <Orders state={state} /> </div> );}

A switch on status reads like a spec of the screen, and TypeScript narrows each case: state.message only exists in the error branch, and state.data only in success. Add a default with a never check (the useReducer lesson shows it) and adding a new status becomes a compile error everywhere it is not handled.

Two refinements matter once real users are involved. First, refetching: when data is already on screen and you reload it, do not swap the content for a spinner. Keep showing the old data with a small "updating" hint. Data libraries split the two ideas for you; TanStack Query v5 has isPending (no data yet) and isFetching (any request in flight, including background ones). Second, the empty state is a design job, not an afterthought: say what will appear here and offer the next action. Interviewers and reviewers notice when every state of a component has been thought about.

Quick check
With separate isLoading, error and orders state, a retry after a failure shows the new orders under the old error message. Why can the Remote union not have this bug?
Need a nudge? A hint rules out a wrong answer.

Hiding vs unmounting

That tip is the short version. There are three ways to make something disappear, and they behave differently in ways that matter for drafts, video players, chat connections and performance.

{open && <Panel />}CSS: hidden or display: none<Activity mode="hidden">
State while hiddenDestroyedKeptKept
DOM while hiddenRemovedKept, invisibleKept, set to display: none
Effects while hiddenCleaned upKeep runningCleaned up, run again when shown
Updates while hiddenNoneRendered at normal priorityRendered at low priority
CostRemount when shown againAlways rendered and runningMemory for the hidden tree

Unmounting is the default and usually right: hidden things cost nothing. Its downside is that coming back starts from scratch. CSS hiding keeps everything, but the hidden part is still fully alive: its timers tick, its video keeps loading, its subscriptions keep firing, and every update re-renders it at full priority. <Activity> (stable since React 19.2) is the middle path: React keeps the state and the DOM, hides it with display: none, cleans up its effects as if it had unmounted, and processes any updates to it only when nothing more urgent is waiting.

Type a draft in Compose, open Inbox, then come back. Then try each strategy.

React
import { Activity, useState } from "react"; type Strategy = "unmount" | "css" | "activity"; function Compose() { const [draft, setDraft] = useState(""); return <textarea aria-label="Draft" placeholder="Write a message..." value={draft} onChange={(e) => setDraft(e.target.value)} />;} export default function App() { const [tab, setTab] = useState<"compose" | "inbox">("compose"); const [strategy, setStrategy] = useState<Strategy>("unmount"); const showCompose = tab === "compose"; return ( <div style={{ display: "grid", gap: 8, maxWidth: 360 }}> <label> Strategy{" "} <select aria-label="Strategy" value={strategy} onChange={(e) => setStrategy(e.target.value as Strategy)}> <option value="unmount">Unmount with &&</option> <option value="css">Hide with the hidden attribute</option> <option value="activity">Activity</option> </select> </label> <div style={{ display: "flex", gap: 6 }}> <button onClick={() => setTab("compose")}>Compose</button> <button onClick={() => setTab("inbox")}>Inbox</button> </div> {strategy === "unmount" && showCompose && <Compose />} {strategy === "css" && <div hidden={!showCompose}><Compose /></div>} {strategy === "activity" && ( <Activity mode={showCompose ? "visible" : "hidden"}> <Compose /> </Activity> )} {!showCompose && <p>Inbox: 3 new messages.</p>} </div> );}

How to choose:

  • Unmount when coming back fresh is fine, or correct (a closed modal, a finished wizard).
  • Use Activity for tabs, side panels and back navigation where users expect their place to be kept, or to render a likely next screen early in the background.
  • Use CSS hiding for small things that toggle often, like a dropdown, where the hidden part has no effects and remounting would cost more than keeping it.
  • Lift the state up when only the data needs to survive, not the whole component. You will learn that in the lifting state lesson.

The effect-events-and-activity lesson goes deeper into Activity, including what happens to effects and how pre-rendering works.

Match the pairs0/4 matched

Match each requirement to the approach that fits best.

Choose an item, then its match on the other side.
ChallengeEasy

Order status

Finish the OrderStatus component. For each order it renders a <div className="order"> containing a message and an item count, except cancelled orders, which render nothing at all.

statusmessage
"loading"Loading...
"shipped"On its way
"delivered"Delivered
"cancelled"render null

After the message, show the count in a <span> as · 2 items (or · 1 item for exactly one). When items is 0, show no count, and make sure no stray 0 appears.

Loading... · 2 items
On its way
Delivered · 1 item
React
type Status = "loading" | "shipped" | "delivered" | "cancelled"; function OrderStatus({ status, items }: { status: Status; items: number }) { // Return null for cancelled orders, otherwise a div.order with the message and count. return null;} const orders: { id: number; status: Status; items: number }[] = [ { id: 1, status: "loading", items: 2 }, { id: 2, status: "shipped", items: 0 }, { id: 3, status: "delivered", items: 1 }, { id: 4, status: "cancelled", items: 5 },]; export default function App() { return ( <div> {orders.map((o) => ( <OrderStatus key={o.id} status={o.status} items={o.items} /> ))} </div> );}
ChallengeMedium

Tabs

Build a tabs component with three tab buttons: Profile, Billing and Security.

  • Profile is selected at first.
  • Below the buttons, a <div role="tabpanel"> shows only the selected tab's text: Profile settings, Billing settings or Security settings.
  • Each button has role="tab" and aria-selected set to true for the selected one and false for the others (screen readers announce this).
  • Clicking a button selects it.

Use useState to remember the selected tab.

React
import { useState } from "react"; const TABS = ["Profile", "Billing", "Security"]; export default function App() { // Remember the selected tab with useState. return ( <div> <div role="tablist"> {TABS.map((tab) => ( <button key={tab} role="tab"> {tab} </button> ))} </div> <div role="tabpanel">Profile settings</div> </div> );}
Key terms
early return
Returning different JSX (or null) from an if before the main return. Clearest for whole-component branches.
ternary in JSX
cond ? <A /> : <B /> picks one of two elements inline.
logical &&
cond && <A /> renders A when cond is truthy and the falsy value otherwise. Make cond a boolean to avoid a stray 0.
return null
A component returning null renders nothing. Not an error.
position identity
React keeps a component's state while the same type renders at the same position in the tree.
discriminated union state
One state value whose status field decides which other fields exist, so impossible combinations cannot be stored.
conditional attribute
An attribute set from an expression. undefined removes it; aria-* and data-* turn booleans into strings.
Activity
React 19.2 component that hides its children while keeping their state and DOM, and cleans up their effects.