Memoization

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

Memoization

Memoization is a computer science optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

In the context of React, memoization is the core concept behind preventing unnecessary re-renders and avoiding redundant calculations.

How Memoization Works (Conceptually)

Imagine you have a function that calculates the factorial of a large number. It takes 5 seconds to run.

// Without memoization
function slowFactorial(n) {
  // ... 5 seconds of math ...
  return result;
}

slowFactorial(100); // Takes 5s
slowFactorial(100); // Takes another 5s!

If we memoize this function, we give it a “memory” (a cache).

// With memoization
const cache = {};

function memoizedFactorial(n) {
  // Check if we already did this math
  if (cache[n]) {
    return cache[n]; // Instant!
  }
  
  // If not, do the math and save it
  const result = /* ... 5 seconds of math ... */;
  cache[n] = result;
  return result;
}

memoizedFactorial(100); // Takes 5s
memoizedFactorial(100); // Instant! Returning cached result.

Memoization in React

React applies this exact concept to its rendering cycle using specific APIs.

Instead of an arbitrary cache object, React uses the dependency array to know when inputs have changed. It compares the current inputs (props or state) to the previous inputs using Object.is (referential equality).

  1. React.memo: Memoizes an entire component. If the props haven’t changed, React returns the cached JSX result instead of calling the component function again.
  2. useMemo: Memoizes the result of a regular function. If the dependencies haven’t changed, React returns the cached value instead of re-running the function.
  3. useCallback: Memoizes a function definition. If the dependencies haven’t changed, React returns the exact same function reference from the previous render.

The Cost of Memoization

Memoization is not free.

Every time you use React.memo or useMemo, React has to allocate memory to store the previous results, and it has to spend CPU time iterating through the dependency array comparing previous values to current values.

If you memoize a very fast, simple function (like a + b), the cost of checking the cache is actually higher than just doing the math again. This is why you should only memoize genuinely expensive operations or when you specifically need to preserve referential equality to prevent cascading re-renders.

Interview Questions

Q: What is memoization in the context of React?
A: Memoization is an optimization technique that stores the results of expensive function calls, component renders, or objects. When the exact same inputs (props or dependencies) occur again, React simply returns the cached result instead of re-calculating it.