What is Memoization?
You'll learn how memoization helps React avoid repeating expensive calculations by remembering previous results.
The Core Idea
Imagine you're at a restaurant and order a complicated dish that takes 30 minutes to prepare. If you order the exact same thing again the next day, it would be wasteful for the chef to start from scratch if they could just heat up a perfectly preserved version from yesterday.
Memoization is exactly this strategy applied to computation: instead of recalculating the same result every time, you cache (store) the result the first time and return the cached version when the inputs haven't changed.
How It Works
When you memoize a function:
- The function runs with specific inputs
- The result is stored in a cache along with those inputs
- Next time the function is called with the same inputs, it returns the cached result immediately
- If the inputs change, it recalculates and updates the cache
Why This Matters in React
React components can re-render frequently. Without memoization, expensive computations—like filtering a large list, performing complex calculations, or transforming data—would run on every render, even when the inputs haven't changed. This wastes CPU cycles and can make your app feel sluggish.
Memoization says: "Only do the hard work again if the inputs actually changed."
A Simple Analogy
Think of memoization like a smart calculator that remembers: "Last time you asked for 2,453 × 789, the answer was 1,935,417. Since you're asking again with the same numbers, here's that answer—no calculation needed!"
Key Takeaway: Memoization caches expensive computation results so you don't repeat the same work when inputs haven't changed, saving time and improving performance.