Sub topic 12
Rendering nothing with null
This chapter assumes you can write function components and pass props. It also assumes you know useState and have seen if, ternary, and && used for conditional rendering in JSX. Here you will learn exactly what React draws for null and the other "empty" values. You will also learn how a component that returns null differs from one that is not rendered at all.
What React draws for empty values
A component must return something React can render. Sometimes the right answer is "nothing." React has a defined set of values that produce no output:
| Value | Renders on screen? |
|---|---|
| `null` | No |
| `undefined` | No (as a component's return value, this needs React 18 or later) |
| `true` | No |
| `false` | No |
| `""` (empty string) | No visible output (React creates an empty text node) |
| `0` | Yes, the character 0 |
| `NaN` | Yes, the text "NaN" |
The first four are what make {condition && <Thing />} work. When the condition is false, the expression evaluates to false, and React skips it. The 0 and NaN rows are why that pattern has a pitfall, which you may remember from the section on &&.
Of these values, null is the one to choose on purpose. It states "I deliberately render nothing here," while undefined often appears by accident, as in a forgotten return.
Returning null from a component
A component can decide it has nothing to show and return null. This is a common way to build components that appear only under some condition.
function UnreadBadge({ count }) {
if (count === 0) {
return null;
}
return <span className="badge">{count}</span>;
}
function Header({ unread }) {
return (
<header>
<h1>Inbox</h1>
<UnreadBadge count={unread} />
</header>
);
}The parent writes <UnreadBadge count={unread} /> unconditionally. The badge owns the rule for when it appears. This keeps the parent simple, and the same rule applies everywhere the badge is used.
The alternative is to put the condition in the parent:
function Header({ unread }) {
return (
<header>
<h1>Inbox</h1>
{unread > 0 && <UnreadBadge count={unread} />}
</header>
);
}Both are valid. The next section explains how they differ.
Returning null is not the same as not rendering
When a component returns null, React still calls the function. The component stays in the tree as a mounted instance, and it just has no DOM output. Three consequences follow:
- Its state is preserved while it returns
null. - Its effects (
useEffect) still run according to their dependencies. - It still re-renders when its props, state, or context change.
When the parent leaves the component out, as in {show && <Widget />}, React unmounts it. Its state is discarded, and its effect cleanups run. If it appears again later, it starts fresh.
The next example shows the difference. Both versions hold a counter that starts at 0.
import { useState } from 'react';
function Counter({ visible }) {
const [count, setCount] = useState(0);
if (!visible) {
return null;
}
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
function App() {
const [visible, setVisible] = useState(true);
return (
<>
<label>
<input
type="checkbox"
checked={visible}
onChange={e => setVisible(e.target.checked)}
/>
Show counter
</label>
<Counter visible={visible} />
</>
);
}Click the button a few times, uncheck the box, then check it again. The count is still there, because Counter never unmounted. Now change App to render {visible && <Counter visible />}. After the same steps the count resets to 0.
Neither behavior is wrong. Pick the one you want:
- Use
return nullinside the component when its state should survive being hidden, such as a half-typed draft in a collapsible panel. - Omit it from the parent when hiding should reset it, such as a form you want blank on reopening.
Do not return null before your hooks
An early return null is easy to place too high. Hooks must be called in the same order on every render, so every hook has to run before any conditional return.
This code breaks the rule:
import { useState } from 'react';
function Panel({ open }) {
if (!open) {
return null; // returns before useState on some renders
}
const [text, setText] = useState('');
return (
<textarea value={text} onChange={e => setText(e.target.value)} />
);
}When open flips from false to true, React sees an extra hook and reports an error about a changed number of hooks. The fix is to call the hook first:
import { useState } from 'react';
function Panel({ open }) {
const [text, setText] = useState('');
if (!open) {
return null;
}
return (
<textarea value={text} onChange={e => setText(e.target.value)} />
);
}The linter rule react-hooks/rules-of-hooks catches this mistake. Keep it enabled.
null inside lists
A map callback can return null for items that should not appear:
function Tasks({ tasks }) {
return (
<ul>
{tasks.map(task =>
task.archived ? null : <li key={task.id}>{task.title}</li>
)}
</ul>
);
}This works, and React ignores the null entries. Keys are only needed on the elements, so the null entries do not need one. Still, filter followed by map usually reads better, and you can reuse the filtered array to check for an empty state:
function Tasks({ tasks }) {
const active = tasks.filter(task => !task.archived);
if (active.length === 0) {
return <p>No active tasks.</p>;
}
return (
<ul>
{active.map(task => (
<li key={task.id}>{task.title}</li>
))}
</ul>
);
}With the null-in-map version, the <ul> renders even when every task is archived. You get an empty bullet list with nothing in it. The filter version can detect that case, because it knows how many items will really appear.
Common mistakes
Forgetting to return. A function that never reaches a return yields undefined. In React 18 and later this renders nothing, with no error, and the component quietly appears empty. Older versions throw an error. This often happens with braces and an arrow function:
// Bug: the braces make this a function body with no return
const Greeting = ({ name }) => {
<h1>Hello, {name}</h1>;
};
// Fixed: parentheses return the JSX
const GreetingFixed = ({ name }) => (
<h1>Hello, {name}</h1>
);Expecting a boolean to print. {isOpen} renders nothing, whether isOpen is true or false. To show the value as text, convert it first:
function Status({ isOpen }) {
return <p>Open: {String(isOpen)}</p>;
}Using null where the layout needs a placeholder. A component that returns null leaves no element behind, so the surrounding layout can shift when it appears. If shifting is a problem, render an element with reserved size instead, such as an empty <div className="badge-slot" />.
Hiding with null what the user needs to understand. A missing section with no explanation can look like a bug. For lists, prefer a short empty-state message, as in the Tasks example above.
Choosing between the approaches
| Situation | Approach |
|---|---|
| Component should appear only when a prop meets a rule, and the rule belongs to the component | Return `null` inside the component |
| Parent decides, and hiding should reset state | `{show && <Widget />}` in the parent |
| Hidden state must survive | Return `null` inside the component |
| Two alternatives, both visible content | Ternary |
| One optional piece with a boolean condition | `&&`, with the left side a real boolean |
| Optional piece where one branch is nothing | Ternary with `null`, for example `cond ? <A /> : null` |
The ternary with null is the explicit version of &&. It is longer, but it avoids the 0 pitfall because the result is always either an element or null.
Exercise
A Notification component keeps a dismissedOnce flag in useState. In App A, the parent renders <Notification show={visible} />, and Notification does if (!show) return null; after its hooks. In App B, the parent renders {visible && <Notification />}. The user hides, then shows the notification. In which app is dismissedOnce still set, and why? Also, what happens if if (!show) return null; is placed above the useState call?
Show answer
In App A, dismissedOnce is still set. The component returns null but stays mounted, so React keeps its state. In App B, the parent stops rendering the component, so it unmounts and its state is discarded. When it shows again, dismissedOnce starts from its initial value. If the early return is placed above useState, the hook runs on some renders and not others. That breaks the rules of hooks, and React reports an error about a changed number of hooks when show changes.
Exercise
What does <p>{count && <b>{count} new</b>}</p> display when count is 0, and how would you change it so it displays nothing?
Show answer
It displays the character 0, because 0 && ... evaluates to 0, and React renders numbers. Make the left side a boolean, as in {count > 0 && <b>{count} new</b>}. You could also use {count ? <b>{count} new</b> : null}.