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.
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.
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.
While loading, the early return renders only the spinner. Nothing else exists in the DOM.
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".
<div>{if (ok) { <p>Yes</p> }}</div> fail to compile?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.
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.
What text does this render?
const items = [];
<p>Cart {items.length && <b>{items.length} items</b>}</p>The fix is always to make the left side a boolean: count > 0 &&, !!count &&, or Boolean(count) &&.
0 when n is 0? Pick all that apply.None picked yet
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.
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:
undefinedornullremoves the attribute. That is whyaria-current={isActive ? "page" : undefined}only appears on the active link.- Boolean HTML attributes such as
disabled,hidden,checkedandrequiredare left out whenfalseand written whentrue. aria-*anddata-*attributes turn booleans into strings.aria-expanded={false}writesaria-expanded="false", which is exactly what screen readers want. Butdata-open={false}writesdata-open="false", and a CSS selector[data-open]still matches it, because the attribute exists. Passundefinedwhen 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>.
[data-open] .menu { display: block; } and you render <div data-open={isOpen}>. What happens when isOpen is false?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.
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>;Pick the clearest tool for each situation.
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.
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.
Ternary: one slot, and it always holds a Counter. Switching only changes the name prop, so the score survives.
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
keymakes 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 thekeyreset 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.
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" />}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.
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.
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?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 hidden | Destroyed | Kept | Kept |
| DOM while hidden | Removed | Kept, invisible | Kept, set to display: none |
| Effects while hidden | Cleaned up | Keep running | Cleaned up, run again when shown |
| Updates while hidden | None | Rendered at normal priority | Rendered at low priority |
| Cost | Remount when shown again | Always rendered and running | Memory 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.
How to choose:
- Unmount when coming back fresh is fine, or correct (a closed modal, a finished wizard).
- Use
Activityfor 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 each requirement to the approach that fits best.
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.
status | message |
|---|---|
"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 itemTabs
Build a tabs component with three tab buttons: Profile, Billing and Security.
Profileis selected at first.- Below the buttons, a
<div role="tabpanel">shows only the selected tab's text:Profile settings,Billing settingsorSecurity settings. - Each button has
role="tab"andaria-selectedset totruefor the selected one andfalsefor the others (screen readers announce this). - Clicking a button selects it.
Use useState to remember the selected tab.
- early return
- Returning different JSX (or
null) from anifbefore the mainreturn. 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 stray0.- return null
- A component returning
nullrenders 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
statusfield decides which other fields exist, so impossible combinations cannot be stored. - conditional attribute
- An attribute set from an expression.
undefinedremoves it;aria-*anddata-*turn booleans into strings. - Activity
- React 19.2 component that hides its children while keeping their state and DOM, and cleans up their effects.