CodeBlanks Logo Icon CodeBlanks

What is useMemo?

Learn to cache an expensive computation with useMemo.

What is useMemo?

useMemo is a hook that recomputes an expensive calculation only when its dependencies change. Use it as const value = useMemo(() => compute(a, b), [a, b]);.

On every render, React returns the cached value instead of calling compute. The function runs again only when a or b changes. This is a speed boost for filtering large lists or doing complex math.

Two cautions: caching costs memory; wrapping tiny computations may be slower. Also, dropping useMemo and trusting React's speed is often fine. Use it only for genuinely slow computations.

Expensive computation example

A list has 1000 items and the user types a search query. If items.filter(i => i.name.includes(query)) runs on every render, 1000 rows are scanned each time.

With useMemo(() => items.filter(i => i.name.includes(query)), [items, query]), filtering runs only when items or query changes. Other renders read from cache.

This brings a serious speed boost for big lists. But on small lists (<50 items) it's not noticeable; it may even add overhead. Adding useMemo without profiling isn't a good habit.

Practice Filter with useMemo

Complete the skeleton. Write a SearchList component. Take ({ '{ items, query }' }). Compute visible with useMemo(() => items.filter(i => i.name.includes(query)), [items, query]). Inside <ul>, render visible.map(i => <li key={ '{ i.id }' }>{ '{ i.name }' }</li>). Export it.

Starter code

App.jsx
import { useMemo } from "react";

// Write the SearchList component here

Sample solution

App.jsx
import { useMemo } from "react";

function SearchList({ items, query }) {
  const visible = useMemo(() => items.filter((i) => i.name.includes(query)), [items, query]);
  return (
    <ul>
      {visible.map((i) => (
        <li key={i.id}>{i.name}</li>
      ))}
    </ul>
  );
}

export default SearchList;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is useMemo used?

  • To recompute every render
  • To cache an expensive computation Correct answer
  • Instead of useEffect
  • To update DOM

Explanation: To cache expensive computations.

2 Dependency

Question
The second argument of useMemo is the ____ array.
Answer
The second argument of useMemo is the dependency array.

Explanation: Second arg is the dependency array.

3 Match the useMemo steps

Term Meaning
compute Compute
deps Dependencies
cache Cache
recompute Recompute

All lessons in Intermediate