CodeBlanks Logo Icon CodeBlanks

useMemo

Learn computation memoization with useMemo.

What is useMemo?

useMemo is a hook that caches the result of an expensive computation. Instead of redoing the computation on every render, it returns the cached result until the dependencies change. You call it as const total = useMemo(() => a + b, [a, b]).

Heavy computations (sorting a big array, filtering, complex math) block the render path. useMemo runs that work only when a or b changes. For cheap operations the memo overhead outweighs the benefit; use it only for truly costly computations. If the same value is needed in several places, one useMemo can be shared.

A computation cache

useMemo takes two parameters: a compute function and a dependency array. The compute function returns a value; that value is cached. Until the dependencies change, the same value is returned.

Example: const sorted = useMemo(() => items.slice().sort(), [items]). Here the sort is not redone unless items changes. To avoid mutating the array, calling .slice() first is important. Adding every outer variable to the deps array keeps the computation correct. A missing dependency leads to working with stale values and tricky bugs.

Practice Compute a total with useMemo

Write a Cart component. The prices array is already defined: [10, 20, 30]. Compute total with useMemo; dependency array is [prices]. The component returns <Text>{total}</Text>.

Starter code

App.js
// Import useMemo

function Cart() {
  const prices = [10, 20, 30];
  // Compute total with useMemo; deps is [prices]

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

Sample solution

App.js
import { useMemo } from "react";
import { Text } from "react-native";

function Cart() {
  const prices = [10, 20, 30];
  const total = useMemo(() => {
    return prices.reduce((sum, p) => sum + p, 0);
  }, [prices]);
  return <Text>{total}</Text>;
}

Questions and answers

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

1 Match each concept to its role

Term Meaning
useMemo Caches a value
deps array Recompute condition
expensive compute Memo candidate
cheap operation No memo needed

2 The useMemo call

Question
const total = ____(() => a + b, [a, b]);
Answer
const total = useMemo(() => a + b, [a, b]);

Explanation: useMemo caches the computed value.

3 What does useMemo return?

App.js
const total = useMemo(() => a + b, [a, b]);
  • A function
  • The computed value Correct answer
  • Not a hook
  • A callback

Explanation: useMemo returns the computed value.

All lessons in Intermediate