Category: react
useMemo is a React
Published on 04 Mar 2026
Explanation
useMemo is a React Hook used to memoize
(cache) the result of a calculation so it
does not re-run on every render.
Code:
import { useMemo } from 'react';
Explanation
useMemo takes a function and a dependency
array.
The function runs only when the dependencies
change Otherwise,
it returns the previously stored value.
Code:
const memoizedValue = useMemo(() => {
return expensiveCalculation(data);
}, [data]);
Explanation
This example recalculates the sum only
when num1 or num2 changes,
preventing unnecessary
recalculations during re-renders.
Code:
const result = useMemo(() => num1 + num2, [num1, num2] );
Explanation
Without useMemo, the function runs on
every render.
With useMemo,
it runs only when dependencies change,
improving performance.
Code:
Without useMemo: const result = expensiveCalculation(data); With useMemo: const result = useMemo(() => expensiveCalculation(data), [data]);
Explanation
If the dependency array is empty,
the function
runs only once during the initial render.
Code:
useMemo(() => computeValue(), []);