Performance: Conditional component rendering
This affects how quickly the page shows relevant content and how much work the browser does updating the UI.
function MyComponent({ show }) { return ( <div> {show ? <ComponentC /> : <ComponentA />} </div> ); }
function MyComponent({ show }) { return ( <div> <ComponentA /> <ComponentB /> {show ? <ComponentC /> : null} </div> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Render all components regardless of condition | High (many nodes) | Multiple reflows | High paint cost | [X] Bad |
| Render components conditionally based on need | Low (minimal nodes) | Single reflow | Low paint cost | [OK] Good |
condition ? exprIfTrue : exprIfFalse, which matches {condition ? <ComponentA /> : <ComponentB />}.isLoggedIn is false?
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
</div>
);
}function Message({ show }) {
return (
<div>
{show && <p>Hello World!</p> else <p>No message</p>}
</div>
);
}const notifications = [];
function NotificationList() {
return (
<div>
{/* Choose the correct conditional rendering here */}
{notifications.length > 0 ? (
notifications.map((note, index) => <p key={index}>{note}</p>)
) : (
<p>No notifications</p>
)}
</div>
);
}Pass the test and this pattern moves unknown