22 Feb 2022
How many re-renders are too many?
My React component re-renders 5 times. Is this too many? What about 10 times or 20? When should I start optimizing?
How many re-renders are too many?
The number of re-renders is a poor performance metric. A long tree of React components that only return JSX can be re-rendered many times without any performance issues. On the other hand, a single component performing a slow calculation on render can create a performance bottleneck even on the very first mount.
When should I start optimizing?
It's tempting to start optimizing unnecessary re-renders at the very beginning of a project. It may seem that if we don't, the project will spiral out of control, and it would be extremely difficult to fix performance issues later. In practice, when we know how to detect and fix performance bottlenecks, we can do it just as easily at later stages of development.
Therefore, a good strategy is to "build first - optimize later." Prematurely worrying about unnecessary re-renders can slow down the "build" phase for no good reason.
During the optimization phase, we can use lower-end devices or Chrome DevTools CPU throttling to spot actual performance issues earlier.
Using debugging tools
When it comes to fixing performance problems, it's helpful to wait until these problems are evident, then use debugging tools to identify the bottlenecks. There are two main tools in the React ecosystem that allow us to do this:
- React Developer Tools Profiler - How to Detect Slow Renders In React
- Chrome DevTools Profiler - Analyze Runtime Performance