Memoization is an optimization technique where the result of a function call is cached (stored), so that future calls with the same inputs can return the result immediately from cache, instead of recalculating.
🔹 Why Use Memoization?
- Speeds up expensive or repetitive function calls.
- Reduces redundant computations.
- Commonly used in recursion, performance-heavy calculations, and React (e.g.,
useMemo,React.memo).
✅ Simple Example:
function memoizedAdd() {
const cache = {};
return function (num) {
if (cache[num]) {
console.log("Fetching from cache");
return cache[num];
} else {
console.log("Calculating result");
const result = num + 10;
cache[num] = result;
return result;
}
};
}
const add = memoizedAdd();
console.log(add(5)); // Calculating result → 15
console.log(add(5)); // Fetching from cache → 15
✅ Used in React (e.g., useMemo, React.memo)
const memoizedValue = useMemo(() => expensiveCalculation(input), [input]);
📝 In Summary:
Memoization boosts performance by caching function results based on input values, avoiding unnecessary re-computation and improving efficiency—especially useful in heavy loops, recursion, and UI rendering.