Introduction
When React executes operations like filter() and map() every time,
it can slow down your app with each re-render.
useMemo prevents these unnecessary recalculations.
useMemo Basics
const value = useMemo(() => {
return heavyCalculation();
}, [dependency]);
What the above code means
"Recalculate only when dependencies change,
use the previous results otherwise."
Example: Optimizing filter processing
const filteredSpots = useMemo(() => {
return spots.filter((spot) => {
if (filters.wifi && !spot.wifi) return false;
if (filters.power && !spot.power) return false;
return true;
});
}, [spots, filters]);
What the above code means
Re-execute only when spots and filters change
Do not recalculate when other state changes, such as clicking a pin
Prevent unnecessary filter() calls for faster performance
Summary
useMemo is a hook that "remembers the calculation result."
Recalculate only when the value written inside [] changes.
Used to optimize heavy processing (filter, sort, reduce).
Top comments (2)
Excellent and simple explanation!
Perfect for beginners.
Clear, concise, and easy to understand how useMemo improves performance in real-world cases.
Thanks so much, Lin! I'm really glad you found it clear and useful 😊
I tried to keep the explanation as simple as possible for beginners.