Inline vs Extracted Mapping Functions
What you'll learn: When to keep your .map() logic directly in JSX versus pulling it into a separate function for better code organization.
The Two Approaches
You've been using .map() to render lists. Now it's time to decide: should you write the mapping logic right inside your JSX, or extract it to its own function?
Inline mapping keeps everything in the return statement:
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
Extracted mapping pulls the logic out:
const renderItem = (item) => {
return <li key={item.id}>{item.name}</li>;
};
return (
<ul>
{items.map(renderItem)}
</ul>
);
When to Keep It Inline
Use inline .map() when the mapping logic is simple — typically just one or two JSX elements with minimal logic. If you can read it easily at a glance, keep it inline. Most simple lists fall into this category.
When to Extract
Extract your mapping function when:
- The JSX inside
.map()spans more than 3-4 lines - You're doing calculations or transformations on each item
- The same mapping pattern repeats elsewhere
- Your return statement feels cluttered and hard to scan
Think of it like cooking: simple recipes stay on one card, but complex dishes deserve their own dedicated instruction page.
Practical Example
// Too complex for inline
{items.map(item => {
const discount = item.price * 0.1;
const finalPrice = item.price - discount;
return (
<div key={item.id}>
<h3>{item.name}</h3>
<p>Original: ${item.price}</p>
<p>Discounted: ${finalPrice}</p>
</div>
);
})}
// Better extracted
const renderProduct = (item) => {
const discount = item.price * 0.1;
const finalPrice = item.price - discount;
return (
<div key={item.id}>
<h3>{item.name}</h3>
<p>Original: ${item.price}</p>
<p>Discounted: ${finalPrice}</p>
</div>
);
};
return <div>{items.map(renderProduct)}</div>;
Key Takeaway: Keep .map() inline for simple lists; extract to a named function when the mapping logic becomes complex or spans multiple lines, making your JSX easier to read and maintain.