Fundamentalsbeginner
Conditional Rendering Patterns
Learn the idiomatic ways to render UI conditionally in JSX and the tradeoffs between each approach.
React doesn't have special template syntax for conditionals — you use plain JavaScript expressions inside JSX. The most common patterns are the ternary operator for either/or rendering, the logical && operator for render-or-nothing cases, and early returns from the component function for entirely different layouts.
JSX conditionals are like a light switch wired directly to a sensor: React doesn't have a special 'if' fixture, it just watches whatever value the sensor (your JavaScript expression) produces and lights up accordingly — including lighting up the digit '0' if that's literally what came through.
Key Concepts
1
Each pattern fits a different shape of problem. Ternaries work well for two mutually exclusive branches, like showing a spinner or the loaded content. The && operator is convenient for optionally showing an element, but it has a well-known gotcha with falsy numeric values.
&&
2
Early returns are useful when a condition should replace the entire render output, such as returning a loading skeleton or an error message before reaching the main component body — this keeps the main return statement free of deep nesting.
3
Interviewers often ask candidates to spot the bug in {count && <Badge count={count} />}: if count is 0, JSX renders the literal text "0" instead of nothing, because 0 is falsy but is still a renderable value in React. The fix is an explicit boolean comparison like count > 0 && <Badge /> or a ternary with null.
{count && <Badge count={count} />}count0count > 0 && <Badge />null