
Learn the useMemo Hook in React
1 October, 2022
7
7
0
Contributors
What is the useMemo hook?
The React useMemo
returns a memoized value.
Think of memoization as caching a value so that it does not need to be recalculated.
It only runs when one of its dependencies update, hence improving performance.
The
useMemo
and theuseCallback
Hooks are similar. The difference is thatuseMemo
returns a memoized value anduseCallback
returns a memoized function. To learn more about theuseCallback
Hook, check out my show on it, Learn the useCallback Hook in React.
Syntax
When to use the useMemo Hook?
The useMemo
Hook can be used to keep expensive, resource intensive functions from needlessly running.
In this example, we have an expensive function that runs on every render.
When changing the count or adding a todo, you will notice a delay in execution.
Example
We’ll notice that the expensiveCalculation runs on every render.
Solution
Wrap the expensiveCalculation(count)
in a useMemo()
.
Here, we’ll notice the expensiveCalculation only re-renders when the count dependency changes.
react
javascript
reacthooks