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.
expensive calculations
? react
examples? useMemo
is good for performance optimization?First of all, you should know that you can only memoize pure functions, that is functions whose output purely depends on their 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 especially 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 in React maybe 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 another object or array.
In such as case useMemo
is really helpful. If the array and the filter criteria remain the same across re-renders, the calculation is not done again instead the previously calculated data is returned from the cache. Remember, memoized data is stored in memory, so make sure you are using it when needed.