Performance: Embedding expressions in JSX
Embedding expressions in JSX affects rendering speed and re-rendering efficiency by controlling how dynamic content updates in the UI.
function Greeting({ user }) { const fullName = `${user.firstName} ${user.lastName}`; return <div>{fullName} is logged in</div>; }
function Greeting({ user }) { return <div>{user.firstName + ' ' + user.lastName + ' is logged in'}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Complex expressions inside JSX | No extra DOM nodes | No direct reflows | Higher CPU usage delaying paint | [X] Bad |
| Precomputed expressions outside JSX | No extra DOM nodes | No direct reflows | Lower CPU usage, faster paint | [OK] Good |
name inside a <p> tag to display it?{} to be evaluated and rendered.name, write it inside curly braces within the JSX tag: {name}.{2 + 3} will calculate the sum.2 + 3. Other options treat it as plain text or incorrect syntax.function Greeting() {
const hour = 10;
return <h1>Good {hour < 12 ? 'Morning' : 'Evening'}!</h1>;
}hour is 10, which is less than 12, so the condition hour < 12 is true.<h1>Good Morning!</h1>.const count = 5;
return <div>You have {count} new messages</div>;count is correctly embedded inside curly braces {count} within JSX.function ListItems() {
const items = ['Apple', 'Banana', 'Cherry'];
return (
<ul>
{items.map(item => <li key={item}>{item.length > 5 ? item : 'Short'}</li>)}
</ul>
);
}item.length > 5 is true for 'Banana' and 'Cherry', false for 'Apple'.<li> has a unique key from the item string, so no error occurs.Pass the test and this pattern moves unknown