DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

A simple explanation of React's useMemo: A mechanism that simply remembers the results

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]);
Enter fullscreen mode Exit fullscreen mode

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]);
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
linjunjie525 profile image
Lin JunJie

Excellent and simple explanation!
Perfect for beginners.
Clear, concise, and easy to understand how useMemo improves performance in real-world cases.

Collapse
 
kazutora_hattori_66972c88 profile image
Kazutora Hattori

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.