Skip to content

Memoization

Optimizing re-renders with React.memo, useMemo, and useCallback.

What you'll learn

  • What memoization is and when it helps performance
  • Using React.memo to prevent component re-renders
  • Using useMemo to cache expensive calculations
  • Using useCallback to stabilize function references

Concept

What Is Memoization?

Memoization is an optimization technique that caches the result of an expensive operation and returns the cached value when the inputs have not changed. In React, memoization prevents unnecessary re-renders and recalculations. However, memoization itself has a cost — comparing inputs and storing cached values — so it should be used judiciously, not on everything. Measure first, then optimize.

React.memo

React.memo is a higher-order component that wraps a component and prevents re-renders if its props have not changed. It does a shallow comparison of props by default. If the parent re-renders but the memoized child's props are the same, the child skips rendering. This is useful for expensive components in lists or components that receive stable props. You can provide a custom comparison function as the second argument for deeper comparisons.

useMemo

useMemo caches the result of a calculation between renders. It takes a factory function and a dependency array: useMemo(() => expensiveCalc(a, b), [a, b]). The calculation runs only when a or b changes; otherwise, the cached value is returned. Use it for genuinely expensive computations (sorting large arrays, complex transformations) or when you need to maintain referential equality of an object/array that is passed as a prop to a memoized child.

useCallback

useCallback caches a function definition between renders. It is equivalent to useMemo(() => fn, deps) but specialized for functions. Its primary use case is passing stable callbacks to memoized child components or as dependencies to other hooks. If a parent creates a new function on every render and passes it to a React.memo child, the child re-renders every time because the function reference changes. useCallback prevents this by returning the same function reference when dependencies are unchanged.

When Not to Memoize

Memoization is not free — React must store the previous value and compare dependencies on every render. For simple values or cheap calculations, the cost of memoization exceeds the savings. Only memoize when you have measured a performance problem or when maintaining referential equality is required for correctness (e.g., as a dependency of useEffect or a prop of a memoized child).

Example

              import { useState, useMemo, useCallback, memo } from "react";

// memo prevents re-render if props are unchanged.
const ExpensiveItem = memo(function Item({ data, onSelect }) {
  console.log("Item rendered");
  return <li onClick={() => onSelect(data.id)}>{data.name}</li>;
});

function ItemList({ items }) {
  const [query, setQuery] = useState("");
  const [selected, setSelected] = useState(null);

  // useMemo caches the filtered list — only recomputes when items or query change.
  const filtered = useMemo(
    () => items.filter(i => i.name.toLowerCase().includes(query.toLowerCase())),
    [items, query]
  );

  // useCallback stabilizes the handler reference for memoized children.
  const handleSelect = useCallback((id) => {
    setSelected(id);
  }, []);

  return (
    <div>
      <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />
      <ul>
        {filtered.map(item => (
          <ExpensiveItem key={item.id} data={item} onSelect={handleSelect} />
        ))}
      </ul>
      <p>Selected: {selected}</p>
    </div>
  );
}
            

memo prevents Item re-renders when props are stable. useMemo caches the filtered list. useCallback keeps handleSelect stable so memoized Items do not re-render unnecessarily.

Try it

  • Code Diff

    Compare performance before and after adding memoization.

  • JSON Formatter

    Inspect large data sets that might benefit from useMemo caching.

Common mistakes

The mistake

Wrapping everything in useMemo and useCallback by default

The fix

Memoization has its own cost (comparison + storage). Use it only for genuinely expensive calculations or to maintain referential equality for memoized children. Measure performance before and after to confirm it helps.

The mistake

Using useCallback without React.memo on the child

The fix

useCallback alone does not prevent re-renders. It only stabilizes the function reference. The child must also be wrapped in React.memo for the stable reference to prevent re-renders. Without memo, the child re-renders regardless.

Practice Memoization

9 exercises

Practice Memoization

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors