This week we’re going to dive into React.memo() and explain how it works, and how it can be beneficial in our code. But first…let’s have a brief overview of how React components work.
React Components, Let’s Review!
Let’s say we had a parent component named Sitcom and a child component name MemoizedSitcom that lists all the products information using a fetch method; every time the parent component (Sitcom) is re-rendered, the child component(MemoizedSitcom) will be re-rendered and fetched as well.
Why should .memo() be used on React.js Components?
It may not seem like a big deal since we’re dealing with only one parent and one child component, but imagine having 100+ components, all re-rendering and fetching for one change. Not only can it present a delayed UI response, but it can cost us loads of money if we’re paying for a cloud database.
Enter, React.memo().
What is React.memo()?
Acting as a higher-order component, when React.memo() wraps a component, React memoizes the rendered output and then skips unnecessary rendering.
Let’s see our new found friend in action. The functional component Sitcom is wrapped in React.memo():
React.memo(Sitcom) returns a new memoized component called MemoizedSitcom. This component outputs the same content as the original Sitcom component, but with one difference. As long as a title or genre props are the same between renderings, React will reuse the memoized content!
You get a performance boost and you avoid unnecessary fetch and re-renders!
Why you shouldn’t alway use React.memo()
What do you mean? Why can’t we always use the .memo() function? It’s amazing and we need it forever and always! Yes, yes, I hear you, however, knowledge comes with power AND responsibility.
“The more often the component renders with the same props, the heavier and the more computationally expensive the output is, the more chances are that component needs to be wrapped in
React.memo()"
- D. Pavlutin
React.memo() should only be used if the following conditions apply:
- Pure Functional Components: Your component is functional and given the same props, which will always render the same output.
- Renders Often
- Re-renders with the same props: Your component is usually provided with the same props during re-rendering
- Medium to large component: Your component contains a decent amount of UI elements to reason props equality check.
General rule of thumb: don’t use memoization if you can’t quantify the performance gains.
Conclusion
Thank you so much for stopping by! I hope that you have a better understanding of React.memo(). Please checkout my online portfolio and feel free to connect with me on Linkedin!
Sources:
https://reactjs.org/blog/2018/10/23/react-v-16-6.html, https://dmitripavlutin.com/use-react-memo-wisely/, https://reactjs.org/blog/2018/10/23/react-v-16-6.html, https://dev.to/guillermodv/using-react-memo-to-skip-unnecessary-rendering-5ae2