Inline Expressions vs Variables Before Return
What you'll learn: How to decide whether to compute JSX values directly inline or extract calculations into variables for cleaner code.
When building JSX, you'll constantly face a choice: should you write logic directly inside your curly braces, or calculate values beforehand and assign them to variables?
The Choice in Action
Both approaches work:
// Inline approach
function UserGreeting({ firstName, lastName }) {
return <h1>Hello, {firstName.toUpperCase()} {lastName.toUpperCase()}!</h1>;
}
// Variable approach
function UserGreeting({ firstName, lastName }) {
const displayName = `${firstName.toUpperCase()} ${lastName.toUpperCase()}`;
return <h1>Hello, {displayName}!</h1>;
}
When to Go Inline
Inline expressions shine when they're short and self-explanatory:
function Price({ amount }) {
return <span>${amount.toFixed(2)}</span>;
}
Simple transformations like .toUpperCase(), basic math, or single ternaries read naturally inline.
When to Extract Variables
Extract to variables when:
- The logic is complex (multiple operations, nested calls)
- You reuse the same value multiple times in JSX
- Readability suffers from cramming too much inline
function OrderSummary({ items, taxRate }) {
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
const tax = subtotal * taxRate;
const total = subtotal + tax;
return (
<div>
<p>Subtotal: ${subtotal}</p>
<p>Tax: ${tax}</p>
<p>Total: ${total}</p>
</div>
);
}
Imagine trying to inline all that calculation logic—your JSX would become unreadable soup.
The Guiding Principle
Think of JSX like a recipe's final presentation instructions. You wouldn't write "combine pre-whisked eggs with pre-sifted flour" in serving directions—you do prep work first, then present. Same here: complex prep goes in variables; simple garnishes can stay inline.
Key Takeaway: Use inline expressions for simple, readable operations; extract complex logic to variables before your return to keep JSX clean and maintainable.