React Native
useMemo
Learn memoization with useMemo.
What is useMemo?
useMemo is a hook that caches an expensive computation. When you write const value = useMemo(() => compute(a, b), [a, b]), React runs the computation once and keeps the result until a or b changes.
useMemo runs during render; it is not a side effect, it is a pure computation. It saves heavy work (sorting a big array, filtering a long list) from re-running on every render. If the dependency array [a, b] is wrong, you get a stale value; so put every input of the computation in the array.
When should you use it?
useMemo is not for every computation, only for truly expensive ones. On small computations useMemo adds overhead rather than benefit; React's own diffing is faster. Sorting a list of hundreds of items or filtering a large object are good candidates.
A second use is reference stability: if an object or array gets a new reference on every render, child components that consume it re-render for nothing. With useMemo you keep the same reference and skip those renders. This helps when the child is wrapped with React.memo.
Exercise Filter with useMemo
Write a Search component. Use items (an array of strings) and a query state. With useMemo filter items by query: items.filter(i => i.includes(query)). The dependency array is [items, query]. The component returns <Text>Search</Text>.
Show example solution
import { useMemo, useState } from "react";
import { Text } from "react-native";
function Search() {
const [items, setItems] = useState(["apple", "pear"]);
const [query, setQuery] = useState("");
const filtered = useMemo(() => items.filter(i => i.includes(query)), [items, query]);
return <Text>Search</Text>;
}
Test yourself
-
Write the useMemo dependency
const sorted = useMemo(() => sortItems(items), ____);
Show answer
const sorted = useMemo(() => sortItems(items), [items]);
-
Match the scenario to the decision
- Sort a large list
- Use useMemo
- Small computation
- Skip useMemo
- New object every render
- Stabilize with useMemo
- Network call
- Use useEffect
-
Which is a good scenario for useMemo?
const total = useMemo(() => sum(bigArray), [bigArray]);
- Making a network call
- Computing a total over a large array
- Keeping a button's click count
- Styling a component
Show answer
Computing a total over a large array — Summing a large array is an expensive computation.
Next lesson: Summary - Hooks