useMemo Hook

🪝 Introduction to useMemo

The useMemo Hook is a React Hook that lets you memoize the result of an expensive calculation. Instead of recalculating a value on every render, React stores the previously computed value and recalculates it only when one of its dependencies changes. This helps improve performance in components that perform costly computations.

Important

useMemo is a performance optimization Hook. It should only be used when memoizing a calculation provides a measurable benefit.

🎯 Why Use useMemo?

Every time a component re-renders, JavaScript expressions inside the component are executed again. If a calculation is expensive, repeatedly performing it can slow down the application. useMemo prevents unnecessary recalculations by remembering the previous result until its dependencies change.

  • Avoid repeated expensive calculations.
  • Improve rendering performance.
  • Memoize derived values.
  • Reduce unnecessary work during re-renders.

⚙️ Syntax

Basic Syntax

const memoizedValue = useMemo(() => {
  return expensiveCalculation();
}, [dependencies]);
PartDescription
useMemo()Memoizes a calculated value.
Callback FunctionReturns the value to be cached.
Dependency ArrayDetermines when the value should be recalculated.

🔄 How useMemo Works

Component Renders
React Checks Dependencies
Dependencies Changed?
Component Continues Rendering
Yes → Recalculate Value
No → Return Cached Value

💻 Example 1: Expensive Calculation

Using useMemo

import { useMemo } from "react";

function Numbers({ numbers }) {
  const total = useMemo(() => {
    return numbers.reduce((sum, number) => sum + number, 0);
  }, [numbers]);

  return <h2>{total}</h2>;
}

The total is calculated only when the numbers array changes. Otherwise, React reuses the previously calculated value.

💻 Example 2: Filtering Data

Filtering a List

import { useMemo } from "react";

function ProductList({ products, search }) {
  const filteredProducts = useMemo(() => {
    return products.filter(product =>
      product.name.includes(search)
    );
  }, [products, search]);

  return (
    <ul>
      {filteredProducts.map(product => (
        <li key={product.id}>
          {product.name}
        </li>
      ))}
    </ul>
  );
}

Filtering occurs only when either the product list or the search text changes.

💻 Example 3: Sorting Data

Sorting Items

import { useMemo } from "react";

function Scores({ scores }) {
  const sortedScores = useMemo(() => {
    return [...scores].sort((a, b) => b - a);
  }, [scores]);

  return (
    <ul>
      {sortedScores.map(score => (
        <li key={score}>{score}</li>
      ))}
    </ul>
  );
}

Sorting large datasets repeatedly can be expensive. useMemo ensures sorting happens only when the input array changes.

📊 Without vs With useMemo

Without useMemoWith useMemo
Calculation runs on every render.Calculation runs only when dependencies change.
May reduce performance.Can improve performance for expensive computations.
No cached result.Previously calculated value is reused.

📋 Common Use Cases

Memoize expensive mathematical or business calculations.

Cache filtered collections instead of filtering during every render.

Prevent repeated sorting of large arrays.

Compute derived values from existing props or state efficiently.

📅 Memoization Process

⚠️ Common Mistakes

  • Using useMemo for inexpensive calculations.
  • Providing an incorrect dependency array.
  • Expecting useMemo to prevent component re-renders.
  • Using memoization everywhere without measuring performance.

Warning

useMemo caches the result of a calculation. It does not stop a component from rendering again.

📊 useMemo vs useCallback

FeatureuseMemouseCallback
ReturnsA memoized value.A memoized function.
Primary PurposeCache expensive calculations.Cache function references.
Common UsageFiltering, sorting, derived data.Passing callbacks to child components.

✅ Best Practices

  • Use useMemo only for expensive calculations.
  • Keep dependency arrays accurate and complete.
  • Measure performance before adding memoization.
  • Memoize derived data instead of recalculating it repeatedly.
  • Remember that readability is often more important than unnecessary optimization.

📚 Official Resource

Learn more about useMemo in the official React documentation at React useMemo Documentation.

Summary

The useMemo Hook helps optimize React applications by caching the results of expensive calculations. It recalculates values only when their dependencies change, reducing unnecessary work during rendering. Used appropriately, useMemo can improve application performance while keeping components efficient and responsive.