Course contentsShow
← React
Lesson 867 of 2,39623. useMemo and useCallbackFree lesson

Memoizing Expensive Calculations

Using useMemo to cache the result of computationally heavy operations like filtering or sorting large arrays.

Memoizing Expensive Calculations

What you'll learn: How to use useMemo to cache the result of computationally heavy operations like filtering or sorting large arrays.


The Problem with Recalculating on Every Render

When React re-renders a component, it re-runs all the code in that component's function body. If you have an expensive calculation—like filtering 10,000 items, sorting a massive dataset, or running complex math—React will redo that work on every single render, even when the inputs haven't changed.

This is wasteful and can make your UI sluggish.

How useMemo Solves This

useMemo caches (memoizes) the result of an expensive calculation. React will only recalculate it when one of its dependencies changes. If the dependencies are the same as last render, React returns the cached result instead of running the function again.

Think of it like this: Imagine you're at a coffee shop that always makes your complicated drink the same way. Instead of brewing it fresh every time you walk by the counter, they hand you the one they already made—unless you change your order.

When to Use It

Use useMemo for operations that:

  • Process large arrays (filtering, sorting, mapping)
  • Perform heavy computations (statistical analysis, graph calculations)
  • Are noticeably slow when profiled

Don't use it for cheap calculations like adding two numbers—the memoization overhead isn't worth it.

Example Scenario

Imagine filtering a list of 5,000 products by search term. Without useMemo, every keystroke triggers a re-render and re-filters all 5,000 items. With useMemo, the filtering only happens when the search term or product list actually changes.


Key Takeaway: useMemo caches expensive calculation results, recalculating only when dependencies change—essential for keeping large data operations performant.