Conditional rendering means showing different UI depending on a condition. In React, this usually means rendering one element when a value is true, another element when it is false, or nothing at all.
Real interfaces constantly change based on data. A user might be logged in or logged out. Data might be loading or finished. A list might contain items or be empty. Conditional rendering is how React handles all of these situations cleanly.
function WelcomeMessage({ isLoggedIn }) {
if (isLoggedIn) {
return <h2>Welcome back!</h2>
}
return <h2>Please log in.</h2>
}function Status({ isOnline }) {
return <p>{isOnline ? 'Online' : 'Offline'}</p>
}function Notification({ hasUnread }) {
return (
<div>
<h3>Inbox</h3>
{hasUnread && <span>New messages</span>}
</div>
)
}Sometimes a component should not render anything at all. In that case, it can return null.
function Warning({ show }) {
if (!show) return null
return <p>Warning: Action required.</p>
}One of the most important real-world uses of conditional rendering is handling UI states around data fetching.
function UserList({ loading, error, users }) {
if (loading) return <p>Loading users...</p>
if (error) return <p>Something went wrong.</p>
if (users.length === 0) return <p>No users found.</p>
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
)
}| Pattern | Best use case |
|---|---|
if | Large or multi-branch conditions |
| Ternary | Short true/false output |
&& | Render something only when true |
null | Hide a component completely |
| Mistake | Why it is confusing | Better approach |
|---|---|---|
| Overusing nested ternaries | Becomes hard to read quickly | Move complex logic to if blocks or helper variables |
Using && with values like 0 | Can render unexpected output | Check conditions carefully before using shorthand rendering |
| Ignoring empty and error states | UI feels incomplete | Handle loading, error, and empty states explicitly |
if blocks over deeply nested ternariesnull when a component should not renderConditional rendering lets React interfaces adapt to changing data and user state. Whether you use if, ternaries, &&, or null, the main goal is to show the right UI for the current situation while keeping the code clear and maintainable.
Explore 500+ free tutorials across 20+ languages and frameworks.