The “&&” Trap in React Conditional Rendering
A common misconception in React is treating && like an if statement for conditional rendering. This post explains why that mental model breaks, how JavaScript actually evaluates &&, and why values like 0 can unexpectedly appear in your UI.
At some point when learning React, you’ll probably write something like this:
{count && <h1>Has count</h1>}And you’ll expect:
“If count is falsy, render nothing.”Seems logical, right?
But then something weird happens.
Instead of rendering nothing, React shows:
0That’s the moment you realize:
Something about this mental model is wrong.
The Misconception
It’s very easy to think:
“&& works like an if statement in JSX.”
But that’s not true.
React does not treat && as a special conditional rendering feature.
What Actually Happens
This code:
{count && <h1>Has count</h1>}is just JavaScript:
count && <h1>Has count</h1>And JavaScript has a very specific rule:
A && B → returns A if A is falsy, otherwise returns BLet’s Apply That Rule
If:
const count = 0Then:
0 && <h1>Has count</h1> → 0So React receives:
<div>{0}</div>And renders:
<div>0</div>Why This Feels Wrong
Because we expect:
falsy → nothingBut React actually does:
render whatever the expression returnsWhen It Works vs When It Breaks
Where This Confusion Comes From
If you’ve used Vue:
<h1 v-if="count">Has count</h1>Vue handles this for you:
- Falsy → nothing rendered
But in React:
{count && <h1>Has count</h1>}There is no special handling.
JSX just evaluates JavaScript expressions.
The Correct Mental Model
Instead of thinking:
condition && JSX = if conditionThink:
condition && JSX = return condition OR JSXSafer Alternatives
✅ Use an explicit condition
{count > 0 && <h1>Has count</h1>}✅ Or use ternary
{count ? <h1>Has count</h1> : null}Why This Matters
This is not just a small detail.
It can lead to:
- Unexpected UI (like showing
0) - Hard-to-find bugs
- Confusing behavior in real apps
Final Takeaway
The most important realization is this:
React does not “conditionally render” — JavaScript decides what gets rendered.
And more specifically:
&& is not an if statement — it’s a value selector.