The Conditional Rendering Trap in React. | by Shreyash | Jul, 2026
That Line of Code
When we want to show a component only when data exists, almost every beginner tutorial teaches us to use the logical && (AND) operator. It looks incredibly clean and elegant.
I wanted a notification badge to appear only if a user had unread notifications in their array. So, I wrote what seemed like the most intuitive line of code possible:
const notifications = []; // Started with an empty arrayreturn (
{notifications.length && }
);
On paper, the logic reads perfectly: “If the length of notifications exists, render the badge.”
But when the array is empty, React doesn’t render a blank space. It prints a giant, ugly 0 on the screen.
The Mechanics: What Happens Behind The Scenes
To fix this, we have to pull back the curtain on how JavaScript handles logical shortcuts.
The && operator doesn’t actually return a boolean (true or false) every time it runs. Instead, it evaluates the expression from left to right. The moment it encounters a falsy value on the left side, it stops dead in its tracks and returns that exact falsy value.
Get Shreyash’s stories in your inbox
Join Medium for free to get updates from this writer.
In JavaScript, there are a handful of falsy values:
falsenullundefined""(empty string)NaN0
When my code checked notifications.length, the length was 0. Because 0 is a falsy value, JavaScript immediately stopped executing and returned the actual number 0.
The Time-Saving Fixes
Once you understand that React treats the number 0 like text, fixing it takes less than five seconds. Here are the three best ways to clear the unwanted characters out of your app.
Fix 1: Turn It Into a Real Boolean (The > Operator)
The absolute safest and most readable fix is to make sure the left side of your && operator evaluates to an absolute true or false statement, rather than a Number.
// Clean, precise, and safe
{notifications.length > 0 && }
Now, if the length is 0, the expression evaluates to false. React completely ignores false values, leaving your screen perfectly blank.
Fix 2: The Double Bang Trick (!!)
If you love short syntax and want to force JavaScript to convert a number into a strict boolean, you can prepend the value with two exclamation marks.
// Converts 0 straight into false
{!!notifications.length && }
The first ! flips the 0 to true, and the second ! flips it back to false. It forces the evaluation to a boolean type, keeping your UI clean.
Fix 3: Rely on the Old School “Ternary Operator”
When in doubt, write it out explicitly. Using a ternary operator forces you to define exactly what should happen when the condition isn’t met.
// Explicitly handles both states
{notifications.length ? : null}
By telling React to return null when the array is empty, you guarantee that nothing gets rendered to the DOM.