What is Memoization?
Memoization is a fancy word for caching results. When you have an expensive calculation that takes time or resources, you don't want to redo it every single render. useMemo lets you cache the result of a calculation and only recompute it when its dependencies change. It's like keeping a cheat sheet instead of solving the same math problem over and over.
Think of it this way: every time your component renders, all the code inside runs from top to bottom. If you're calculating something complex - like filtering a large list or doing heavy math - that work happens every render. useMemo says "I already calculated this with the same inputs, so here's the cached result instead."
Caching Expensive Calculations
To use useMemo, you pass it a function and an array of dependencies. The function runs once and caches its result. On subsequent renders, if the dependencies haven't changed, useMemo returns the cached value instead of running the function again. If any dependency changes, the function runs fresh and caches the new result.
function ProductList({ products, filter }) {
const filteredProducts = useMemo(() => {
return products.filter(p =>
p.name.toLowerCase().includes(filter.toLowerCase())
)
}, [products, filter])
return filteredProducts.map(p => (
<li key={p.id}>{p.name}</li>
))
}
Try it Yourself โ
When to Use useMemo
Use useMemo when you have a genuinely expensive calculation. Filtering a list of 10 items? Probably not worth it. Sorting and filtering 10,000 items? Absolutely worth it. The overhead of useMemo itself is tiny, but the savings can be huge for expensive operations.
You should also use useMemo when you're creating objects or arrays that are passed as props to child components. Without memoization, new objects are created on every render, which can cause unnecessary re-renders of children that use React.memo. This is a performance optimization that can make a real difference in large applications.
Performance Implications
Don't go memoizing everything though. useMemo isn't free - it uses memory to store cached values and has a small overhead for checking dependencies. For simple calculations, the overhead might actually be more than just recalculating. It's a tradeoff: you're trading memory for computation time.
The golden rule is to measure first. Use React DevTools Profiler or browser performance tools to see if memoization actually helps. Most of the time, you only need to memoize a few key things. Overusing it makes your code harder to read without any real performance benefit. Use it wisely, and your app will fly.