Part 8: Conditional Rendering: Patterns & Best Practices
In React, you often need to display different UI elements depending on certain conditions (such as authentication status, loading state, or user roles).
1. The Ternary Operator (condition ? A : B)
The most common and clean way to toggle between two elements:
export default function AuthHeader({ isAuthenticated, username }) {
return (
<header className="navbar">
<h1>Devify Platform</h1>
{isAuthenticated ? (
<div className="user-info">
<span>Welcome, {username}!</span>
<button className="btn-logout">Sign Out</button>
</div>
) : (
<button className="btn-login">Sign In</button>
)}
</header>
);
}
2. Logical AND Short-Circuiting (condition && <Element />)
When you want to render an element only when a condition is true, and nothing when it is false:
export default function NotificationBadge({ unreadCount }) {
return (
<div className="inbox">
<span>Messages</span>
{unreadCount > 0 && (
<span className="badge">{unreadCount}</span>
)}
</div>
);
}
⚠️ The Number Zero Gotcha!
In JavaScript, 0 && <Component /> evaluates to 0, which React will print directly to the screen!
// ❌ WRONG: If count is 0, it renders '0' on the screen!
{messages.length && <MessageList />}
// CORRECT: Explicit boolean check
{messages.length > 0 && <MessageList />}
3. Early Return Pattern
For full-page states like loading or fatal errors, early returns keep component code clean:
export default function ArticleView({ article, isLoading, error }) {
if (isLoading) {
return <div className="spinner">Loading article...</div>;
}
if (error) {
return <div className="error-alert">Error: {error.message}</div>;
}
if (!article) {
return <p>No article found.</p>;
}
return (
<article>
<h1>{article.title}</h1>
<p>{article.body}</p>
</article>
);
}
Key Takeaways
- Use ternary operators (
? :) for binary choice rendering. - Use logical AND (
&&) for render-or-nothing, ensuring conditions evaluate to booleans. - Use early returns to simplify complex component branches like loading states.
In Part 9, we will explore Rendering Lists and Keys and dive into the reconciliation algorithm!

