User always enjoy faster and responsive user interface (UI). Unwanted page re-rendering is the key factor which makes web pages slower and less responsive which users never like.
To improve web page performance, React offers React.memo() HOC (high order component).
When React.memo() wraps a component, React memorizes the rendered output and then it skips the unwanted rendering.
In this article, we will see an example of unnecessary re-rendering and how then we can fix that using React.memo()
Below is an example of unwanted user interface re-rendering:
In the above example of code, you could see that the CounterComponent internally renders HeaderComponent and every time increase the count by 1 in case of + button click.
When you try to run the above code then you will notice that whenever + button is click, count increase by 1 which is fine but it also prints “Counter Component” in the browser console that means it renders HeaderComponent.
So every + button click, it re-renders HeaderComponent irrespective msg property which is passed to it is changed or not. It makes user interface slower and less responsive.
You can imagine since its a small example but if we have a complex page having many sections then how unwanted re-rendering impact the performance of the user interface.
Let’s see how we can fix this issue using React.memo()
In the above code, we wrap HeaderComponent using React.memo() and instead using HeaderComponent we used MemoHeaderComponent.
If you try to run the above code then you will notice that now “Counter Component” message will be printed only once to the browser console irrespective how many times + button is clicked.
This means using React.memo(), we are now able to avoid unwanted re-rendering of HeaderComponent.
Note: To handle object properties to memo component, we have an overload of React.memo API.
React.memo(<Component>, (prevProps, nextProps) => (prevProps.obj.name === nextProps.obj.name))
In the above example, if name of obj property is changed only then wrapped component will be re-rendered.
Hope this article will help you to further make your user interfaces faster and responsive!!!