Performance: If conditions in JSX
This affects rendering speed and interaction responsiveness by controlling how many elements React creates and updates in the DOM.
function Component({ show }) { if (!show) return <AnotherExpensiveComponent />; return <ExpensiveComponent />; }
function Component({ show }) { return ( <div> {show ? <ExpensiveComponent /> : <AnotherExpensiveComponent />} {show && <ExpensiveComponent />} </div> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple conditional components rendered simultaneously | High (many nodes created) | Multiple reflows | High paint cost | [X] Bad |
| Single conditional return with if statement | Low (only needed nodes) | Single reflow | Low paint cost | [OK] Good |
isLoggedIn is true?condition && expression renders the expression only if the condition is true.{isLoggedIn && <p>Welcome back!</p>} uses {isLoggedIn && <p>Welcome back!</p>}, which is correct. {if (isLoggedIn) <p>Welcome back!</p>} uses an invalid if statement inside JSX. {isLoggedIn ? <p>Welcome back!</p>} uses an incomplete ternary operator without the false branch (`: expression`), causing a syntax error. {isLoggedIn || <p>Welcome back!</p>} uses ||, which is incorrect for this purpose.<p>Hello</p> if showHello is true, otherwise <p>Goodbye</p>?condition ? expressionIfTrue : expressionIfFalse.{showHello ? <p>Hello</p> : <p>Goodbye</p>} correctly shows Hello if showHello is true, else Goodbye. {showHello && <p>Hello</p> else <p>Goodbye</p>} uses invalid syntax with else inside JSX. {if (showHello) <p>Hello</p> else <p>Goodbye</p>} tries to use if statement inside JSX, which is invalid. {showHello ? <p>Goodbye</p> : <p>Hello</p>} reverses the messages.function Greeting({ isMorning }) {
return (
<div>
{isMorning ? <h1>Good morning!</h1> : <h1>Good evening!</h1>}
{isMorning && <p>Have a nice day!</p>}
</div>
);
}isMorning is false?isMorning ? <h1>Good morning!</h1> : <h1>Good evening!</h1> renders <h1>Good evening!</h1> because isMorning is false.isMorning && <p>Have a nice day!</p> renders nothing because isMorning is false.return (
<div>
{isActive ? <p>Active</p>}
</div>
);condition ? exprIfTrue : exprIfFalse. Here, the false part is missing.map and conditional rendering?{users.map(user => user.isActive ? <li key={user.id}>{user.name}</li> : null)} correctly uses key={user.id} and returns null for inactive users, which React ignores.{users.map(user => if (user.isActive) return <li key={user.id}>{user.name}</li> )} uses invalid syntax: `if` statement directly after arrow function requires block `{}` braces. {users.map(user => user.isActive || <li>{user.name}</li>)} uses `||` which renders items for inactive users and misses keys. {users.map(user => user.isActive ? <li>{user.name}</li> : <li>Inactive</li>)} shows inactive users with text, which is not desired.Pass the test and this pattern moves unknown