useMemo
- React Native course
- Intermediate
- Lesson 5/116
- 5 min
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.
Practice 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>.
Starter code
// Import useMemo
function Search() {
const [items, setItems] = useState(["apple", "pear"]);
const [query, setQuery] = useState("");
// Filter items by query with useMemo
return <Text>Search</Text>;
}Sample 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>;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the useMemo dependency
const sorted = useMemo(() => sortItems(items), ____);
const sorted = useMemo(() => sortItems(items), [items]);
Explanation: items must be in the dependency array.
2 Match the scenario to the decision
| Term | Meaning |
|---|---|
Sort a large list |
Use useMemo |
Small computation |
Skip useMemo |
New object every render |
Stabilize with useMemo |
Network call |
Use useEffect |
3 Which is a good scenario for useMemo?
const total = useMemo(() => sum(bigArray), [bigArray]);- Making a network call
- Computing a total over a large array Correct answer
- Keeping a button's click count
- Styling a component
Explanation: Summing a large array is an expensive computation.