When to Extract vs Inline with useMemo
What you'll learn: How to decide whether to pull computation logic outside your component or keep it inline with useMemo.
You have two good options for avoiding unnecessary recalculations: extracting the computation to a separate function outside your component, or using useMemo to memoize it inline. Knowing which to choose keeps your code clean and performant.
The Decision Framework
Extract outside the component when your computation is pure and independent — it doesn't need any props or state:
// Pure function, no dependencies on component internals
function calculateTax(price) {
return price * 0.15;
}
function Product({ price }) {
const tax = calculateTax(price); // Just call it directly
return <div>Tax: ${tax}</div>;
}
This is better than useMemo because it's simpler, easier to test, and runs fresh each render anyway (which is fine for cheap operations).
Use useMemo inline when your computation depends on props or state:
function ShoppingCart({ items, discountCode }) {
const total = useMemo(() => {
// Needs items and discountCode from props
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
const discount = discountCode === 'SAVE10' ? 0.1 : 0;
return subtotal * (1 - discount);
}, [items, discountCode]);
return <div>Total: ${total}</div>;
}
Here, the calculation needs access to component props, so extraction wouldn't work. useMemo caches the result and only recalculates when items or discountCode change.
The Analogy
Think of extraction like a recipe book on your shelf (always available, no context needed) versus useMemo like a meal-prep container in your fridge (preserves the result using ingredients you had today).
Key Takeaway: Extract pure, independent computations to separate functions; use useMemo for expensive calculations that depend on props or state. Both are better than useEffect for deriving values.