useMemo and useCallback
11 min read
Skipping Expensive Recalculations
useMemo memoizes the result of an expensive computation — it re-runs only when its dependencies change. useCallback memoizes a function reference — useful when passing callbacks to optimized child components.
jsx
import { useMemo, useCallback, useState } from 'react';
function ProductList({ products, discount }) {
// Only recalculates when products or discount changes
const discountedProducts = useMemo(() => {
return products.map(p => ({
...p,
price: p.price * (1 - discount),
}));
}, [products, discount]);
// Stable reference: won't cause child to re-render unnecessarily
const handleBuy = useCallback((productId) => {
console.log('Buying', productId);
}, []); // no deps: function never changes
return discountedProducts.map(p => (
<ProductCard key={p.id} product={p} onBuy={handleBuy} />
));
}Don't over-memoize. Both hooks add overhead (memory + dependency comparisons). Only use them when you've measured a performance problem, or when a function is passed to a React.memo-wrapped child.
Ready to test yourself?
Practice React— quiz & coding exercises