Memoization is a technique of caching the results of a computationally expensive function. In React we can use this technique to avoid unnecessary re-renders and expensive recomputations. React provides three methods for this:
- memo: a higher-order component used for memoizing components.
- useMemo: hook for memoizing a value which is expensive to compute
- useCallback: similar to useMemo, used for memoizing a callback function.
Even though memoization is great for improving performance, if used inappropriately it can have the opposite effect. Let's look at the top three things you should be mindful of before using these methods in your react projects.
1. Memoization is meant for performance optimization
Unless you encounter performance issues in your application, it is probably not a good idea to use any of the memoization methods. Your code should work without memoization(however slow it may be). As a rule of thumb, you should consider optimizing after implementing your components.
If you notice performance issues, the React DevTools can help in finding performance bottlenecks. But also keep in mind that all performance issues can't be solved with memoization. So it is best to always check if there is any improvement gained from it.
2. Memoization has performance overheads
Performance optimizations mostly come with some trade-offs. This is especially true with memoization. By caching previous results, we are using more memory in turn for better speed. So, you should always consider if the cost of memoization is worth it. This depends on the use case, but it is worth noting that there can be an extra overhead to its use if performance improvements are not substantial.
3. React doesn't always guarantee memoization
On the React docs if you see the section on useMemo it reads:
You may rely on useMemo as a performance optimization, not as a semantic guarantee
If you also look at React.memo in the docs you will find this:
This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.
React will cache results for as long as possible, but in some cases, it may also choose to invalidate the cache. So, there is no guarantee that the memoized value has not been discarded. This means you can't rely on React to always memoize values for you. To avoid introducing bugs to your application, always use memoization methods to optimize performance and nothing more.
I hope you now have all the information you need to use memoization in React responsibly. Please do share your comments and suggestions, and thank you for reading.