Performance: Ternary operator usage
This affects rendering speed by controlling conditional rendering efficiently without extra DOM nodes or unnecessary re-renders.
function Component({ isLoggedIn }) { return <div>{isLoggedIn ? 'Welcome back!' : 'Please log in.'}</div>; }
function Component({ isLoggedIn }) { if (isLoggedIn) { return <div>Welcome back!</div>; } else { return <div>Please log in.</div>; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| If-else with multiple returns | Multiple React reconciliation checks | Potential multiple reflows if DOM changes | Higher paint cost due to extra DOM updates | [!] OK |
| Ternary operator inline | Single reconciliation check | Single reflow if DOM changes | Lower paint cost with minimal DOM updates | [OK] Good |
condition ? expr1 : expr2 do in React JSX?condition ? expr1 : expr2, which means it evaluates the condition first.expr1; if false, it returns expr2.expr1 if condition is true, otherwise expr2. -> Option A"Yes" if isActive is true, else "No"?condition ? expr1 : expr2 format.{isActive ? "Yes" : "No"} correctly uses {isActive ? "Yes" : "No"}. Options B, C, and D have syntax errors or incomplete expressions.{isActive ? "Yes" : "No"} [OK]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 false, it chooses the second expression.isLoggedIn is falseisLoggedIn is false, it renders <h1>Please sign in.</h1> inside the div.return (
<div>
{isReady ? <p>Ready</p> : <p>Not ready</p>}
{isReady ? <p>Go!</p> : null}
</div>
);{isReady ? <p>Go!</p> : null} which is valid syntax.null, which is valid JSX.const users = [
{ name: "Alice", online: true },
{ name: "Bob", online: false }
];
function UserList() {
return (
<ul>
{users.map(user => (
<li key={user.name}>
{user.name} - {user.online ? "Online" : "Offline"}
</li>
))}
</ul>
);
}user.online is true, else "Offline".<li> has a unique key from user.name, and the ternary is correctly inside JSX curly braces.Pass the test and this pattern moves unknown