React
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.
Exercise 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.
Show example solution
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;
Test yourself
-
When is useMemo used?
- To recompute every render
- To cache an expensive computation
- Instead of useEffect
- To update DOM
Show answer
To cache an expensive computation — To cache expensive computations.
-
Dependency
The second argument of useMemo is the ____ array.
Show answer
The second argument of useMemo is the dependency array.
-
Match the useMemo steps
- compute
- Compute
- deps
- Dependencies
- cache
- Cache
- recompute
- Recompute
Next lesson: Dependency control