Looking at React's useMemo
documentation. They say to use it when you need to compute an expensive calculation.
This optimization helps to avoid expensive calculations on every render.
I looked at the memoized
link they provide and what I understood is that you can think of it like an cache.
I'm not an expert at computer science, but I know that memoization is a good optimization for calculating fibonacci
I'm still trying to understand better why and how to use useMemo
, but a few things are still unclear to me.
- What is considered
expensive calculations
? - Can someone give real
react
examples? - In what cases
useMemo
is good for performance optimization?
Memoization
is the process of storing a computed value so you don't have to recalculate it again.In react, most common usages are those of values derived from a redux store (for which exists reselect), or a complete memoization of functional components.
There is no golden rule to decide whether a function is expensive and should be memoized, as it depends heavily on your specific use case, and it's performance pitfalls, but usually it is saved for array filtering/sorting, or stuff like that.
The best way to know what should be memoized and what not is to profile your app, see which computations take the most resources and memoize them to see if it makes a difference.
First of all you should know that you can only memoize pure functions, that is functions whose output purely depends on its arguments.
So in short, you would do memoization when you know that most often input remains the same and you wouldn't want to unnecessarily recalculate the result again and again for the same input specially when the calculation is expensive which may mean that the data-set on which computation needs to be performed is large
A case of using memoization is React may be when you are trying to filter data from a large array.
Another case would be when you wish to transform a nested object based on some parameters into other object or array.
In such as case
useMemo
is really helpful. If the array and the filter criteria remains the same across re-renders, the calculation is not done again instead the previously calculated data is returned from the cache