Sub topic 9
Conditional Rendering with if and Early Return
This chapter assumes you know JavaScript arrays, objects, and arrow functions. It also assumes you can write React function components with props and JSX, and that you have used the useState hook. Here you will learn the most basic way to decide what a component shows: plain if statements and early returns.
Components are just functions
A React function component is a JavaScript function that returns a description of the UI. Because it is a function, you can use any JavaScript control flow before the return. That includes if, else, switch, and loops.
JSX itself is different. Inside the JSX markup, you can only embed expressions in curly braces. An if statement is a statement, not an expression, so this does not work:
function Greeting({ user }) {
return (
<div>
{if (user) { <p>Hello, {user.name}</p> }}
</div>
);
}This is a syntax error. Later chapters cover the ternary operator and &&, which are expressions and can sit inside JSX. The approach in this chapter avoids the problem. You make the decision before the return, in ordinary JavaScript.
The early return pattern
An early return means exiting the function as soon as you know what to render, so the rest of the function does not run. Each return produces a complete result for one situation.
function Cart({ items }) {
if (items.length === 0) {
return <p>Your cart is empty.</p>;
}
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}When items is empty, React gets the paragraph and the function ends. Otherwise the code falls through to the list. The main path stays at the bottom and is not nested inside else blocks.
This style is often called a guard clause. Each guard handles one unusual case and gets it out of the way.
Handling several cases in order
Components often have more than two states. Data may be loading, may have failed, or may be ready. Stack the guards from the most exceptional case to the normal one.
function UserList({ users, isLoading, error }) {
if (isLoading) {
return <p>Loading users...</p>;
}
if (error) {
return <p role="alert">Could not load users: {error.message}</p>;
}
if (users.length === 0) {
return <p>No users found.</p>;
}
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Order matters. If the empty check came first, a component that is still loading would briefly claim there are no users. Read the guards top to bottom as a list of questions, where the first "yes" wins.
Returning nothing with null
Sometimes the right answer is to show nothing. A component can return null, and React renders no output for it.
function Banner({ message }) {
if (!message) {
return null;
}
return <div className="banner">{message}</div>;
}The parent can still render <Banner message={text} /> freely. The component decides for itself whether it has anything to show. This keeps the decision close to the data it depends on.
Returning undefined by accident is a different matter. In current React versions a component can return undefined without an error, but it is easy to do by forgetting a return statement. Return null explicitly when you mean "nothing".
Using if with a variable
Early return replaces the whole output. Sometimes you want to change only one piece of a larger layout. For that, assign the piece to a variable and place the variable in the JSX.
function Message({ isLoggedIn, name }) {
let content;
if (isLoggedIn) {
content = <p>Welcome back, {name}.</p>;
} else {
content = <a href="/login">Please log in</a>;
}
return (
<section>
<h2>Account</h2>
{content}
</section>
);
}The heading renders in both cases. Only the content part changes. Use let here because the variable is assigned in one of two branches. A variable holding JSX is a normal value, so it can be null too.
When to prefer which form
| Situation | Better choice |
|---|---|
| The whole component should be replaced in a special case | Early return |
| One section of a shared layout changes | `if` with a variable |
| The logic has three or more branches | `if` or `switch`, before the `return` |
| A tiny inline choice between two values | Ternary (next chapter) |
Hooks and early returns
There is one rule that makes early returns risky. Hooks such as useState must be called in the same order on every render. If you place an early return above a hook call, some renders skip that hook, and React reports an error.
This code is wrong:
import { useState } from 'react';
function Panel({ visible }) {
if (!visible) {
return null;
}
// Called only when visible is true. This breaks the rules of hooks.
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(!open)}>Toggle</button>
{open && <p>Details</p>}
</div>
);
}The fix is to call all hooks first, then return early.
import { useState } from 'react';
function Panel({ visible }) {
const [open, setOpen] = useState(false);
if (!visible) {
return null;
}
return (
<div>
<button onClick={() => setOpen(!open)}>Toggle</button>
{open && <p>Details</p>}
</div>
);
}Note that the state open now exists even while the panel is hidden. If that is not what you want, move the stateful part into its own child component. The parent then decides whether to render the child at all.
Conditional rendering and component state
Where you place a condition affects whether React keeps or discards state.
When a component returns null, React removes it from the screen. Its state is thrown away. If it renders again later, it starts fresh.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
function App() {
const [show, setShow] = useState(true);
return (
<>
<label>
<input
type="checkbox"
checked={show}
onChange={e => setShow(e.target.checked)}
/>
Show counter
</label>
{show ? <Counter /> : null}
</>
);
}Click the counter a few times, hide it, and show it again. It starts at 0 because Counter was removed and then created anew. If you need the count to survive, keep that state in the parent and pass it down as props.
Common mistakes
- Putting
ifinside JSX braces. Statements are not allowed there. Move theifabove thereturn, or use an expression form. - Early return above a hook. Hooks must run on every render in the same order.
- Guards in the wrong order. Check loading and error states before checking whether data is empty.
- Forgetting
return. A branch that builds JSX but never returns it produces nothing, orundefined. - Reading properties of data that may be missing. Guard against
nullorundefinedbefore you useuser.nameoritems.length. - Deep nesting. If you have
ifinsideifinsideelse, flatten it with early returns.
Putting it together
This component uses guards for the page-level states, then a variable for one section of the layout.
function OrderSummary({ order, isLoading }) {
if (isLoading) {
return <p>Loading order...</p>;
}
if (!order) {
return <p>Order not found.</p>;
}
let shipping;
if (order.shipped) {
shipping = <p>Shipped on {order.shippedDate}</p>;
} else {
shipping = <p>Not shipped yet.</p>;
}
return (
<article>
<h2>Order #{order.id}</h2>
<ul>
{order.items.map(item => (
<li key={item.id}>
{item.name} x {item.quantity}
</li>
))}
</ul>
{shipping}
</article>
);
}The guards guarantee that by the time the main return runs, order exists. The code below the guards can then use order.items without checking again.
Exercise
A component calls useState after an if (!user) { return null; } line. It works at first, then React throws an error about hooks when user changes from null to an object. Why does the error happen, and how do you fix it?
Show answer
React expects the same hooks to be called in the same order on every render. On renders where user is null, the early return skips useState, so the hook count differs between renders. Fix it by moving every hook call above the early return, or by moving the stateful part into a child component that only renders when user exists.
Exercise
Write a Notifications component that takes a notifications array of { id, text } objects. It should return null when the array is empty, and otherwise render a keyed ul of the texts. Which statement type makes the decision, and where does it go?
Show answer
Use an if statement before the return: if (notifications.length === 0) { return null; }. Then return <ul>{notifications.map(n => <li key={n.id}>{n.text}</li>)}</ul>. An if is a statement, so it must sit in the function body and not inside the JSX braces.