Performance: Why conditional rendering is needed
Conditional rendering affects how much content the browser needs to process and display, impacting page load speed and interaction responsiveness.
function Component({ showHeavy }) { return ( <div> {showHeavy ? <HeavyComponent /> : null} <LightComponent /> </div> ); }
function Component() { return ( <div> <HeavyComponent /> <LightComponent /> </div> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Render all components unconditionally | High (all nodes created) | Multiple reflows | High paint cost | [X] Bad |
| Render components conditionally | Low (only needed nodes) | Single or fewer reflows | Lower paint cost | [OK] Good |
{condition && <Component />} renders the component only if condition is true.{condition && <Component />} matches the correct syntax exactly. {condition && &<Component />} has an extra & symbol. {condition ? <Component /> : null} uses ternary, which is correct but not && syntax. {condition ? <Component />} is incomplete ternary syntax.function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);
}isLoggedIn is false?isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>. If isLoggedIn is true, it shows "Welcome back!"; otherwise, it shows "Please sign in."false to the conditionisLoggedIn is false, the component renders the second part: <h1>Please sign in.</h1>.function ShowMessage({ show }) {
return (
<div>
{show ? <p>Hello!</p>}
</div>
);
}{show ? <p>Hello!</p>} which is incomplete because ternary requires both true and false parts separated by a colon.{show ? <p>Hello!</p> : null} or another expression after colon.isLoggedIn and isAdmin are true.{isLoggedIn && isAdmin && <AdminMessage />} uses isLoggedIn && isAdmin && <AdminMessage />, which renders the message only if both are true. {isLoggedIn ? <AdminMessage /> : <LoginPrompt />} shows message if logged in regardless of admin. {isAdmin ? <AdminMessage /> : null} ignores logged-in status. {isLoggedIn || isAdmin ? <AdminMessage /> : null} uses OR, showing message if either is true, which is incorrect.Pass the test and this pattern moves unknown