Extracting Computation Outside the Component
What you'll learn: How moving pure functions outside your component can eliminate unnecessary re-execution on every render.
When you have a pure function—one that doesn't need props, state, or any component-specific values—there's no reason for it to live inside your component body.
The Core Problem
Every time your component renders, all functions defined inside it are recreated. If you have a helper function that performs calculations with only its arguments (no closure over component values), you're wastefully recreating that function on every render.
function ProductList({ products }) {
// ❌ Recreated on every render
const calculateDiscount = (price, percentage) => {
return price * (percentage / 100);
};
return products.map(p => (
<div key={p.id}>{calculateDiscount(p.price, 10)}</div>
));
}
The Solution
Move it outside the component entirely. Pure functions that only use their parameters should be defined at the module level:
// ✅ Created once when module loads
const calculateDiscount = (price, percentage) => {
return price * (percentage / 100);
};
function ProductList({ products }) {
return products.map(p => (
<div key={p.id}>{calculateDiscount(p.price, 10)}</div>
));
}
Why This Matters
The function now exists once per module load, not once per render. This is cleaner, more performant, and signals that the function is truly pure—it has no dependencies on component internals.
Think of it like shared utilities: a calculator doesn't need to be rebuilt every time you walk into a room.
Key Takeaway: Pure functions that don't access props, state, or context should live outside your component at the module level—they'll run once at load time instead of recreating on every render.