React Native
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.
Exercise 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>.
Show example solution
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>;
}
Test yourself
-
Match each concept to its role
- useMemo
- Caches a value
- deps array
- Recompute condition
- expensive compute
- Memo candidate
- cheap operation
- No memo needed
-
The useMemo call
const total = ____(() => a + b, [a, b]);
Show answer
const total = useMemo(() => a + b, [a, b]);
-
What does useMemo return?
const total = useMemo(() => a + b, [a, b]);
- A function
- The computed value
- Not a hook
- A callback
Show answer
The computed value — useMemo returns the computed value.
Next lesson: FlatList optimization