DEV Community

Cover image for Avoid unnecessary re-renderings in React.js.
Andrey Germanov
Andrey Germanov

Posted on

Avoid unnecessary re-renderings in React.js.

Did you experience the following: you just open a website in a browser and do nothing, but CPU usage of your computer grows up to 100% if look to System Monitor? RAM almost not used, Network almost not used, but CPU usage is near 100%? Then, you just close a tab in a browser, and CPU usage drops twice or even more very fast? This is a true sign that the website has background operations that recalculate the whole DOM of a page all the time in a loop to re-render it.

If you use React.js with state management, it uses a virtual DOM, and when re-render occurs, React implements a calculation to see a difference between the previous state and the current state and decide which parts of a page DOM tree should be re-rendered. It happens every time a background process changes a state. Even if you need to update a single label on the page, React recalculates the whole component which contains this label. What is more, if re-render event triggered, it recalculates a state change in the component even to decide that nothing should be re-displayed. The calculation is CPU operation, but JavaScript is not the best language for CPU-intensive operations. If the background process updates something every second, then this simple state change can become a CPU-intensive operation. That is why it's important to care about the unnecessary re-rendering of React components. Otherwise, users will stop using your apps, regardless of how beautiful or interactive those apps are.

There are very few reasons to re-render the whole page or root component. In most cases need to re-render only the component, that contains the HTML elements, which should be updated. It's easy to see, how often your components re-render themselves while your website works. Just add "console.log("RERENDER")" to a "render" function of your components and see how often it displays this message in a JS console. If you see something crazy, that this line appears 10 times, for example, but you just click once or even do nothing, then it's time to audit your components to reduce unnecessary renderings. This is an article with some tips on how to do that:

If you know other handy tools either to monitor React components resource usage and/or to optimize performance, post them in comments. It will be very interesting to consider and have a database of these tools and tips.

For now I am happy to add one of the most famous tools to measure website performance. This is LightHouse: .

Discussion (0)