There are a lot of ways to cause unnecessary re-renders in React. But what does unnecessary re-render mean? Does it mean that the browser re-renders the piece of UI associated with a component?
In the example above, components A, B and C re-render in response to App render. Let’s open developer tools and take a look at what happens in the DOM.
Even though React re-renders every component in the tree, it doesn’t update every node in the DOM. React only updates a text node that is supposed to change visually.
A key part of this to understand is that “rendering” is not the same thing as “updating the DOM”, and a component may be rendered without any visible changes happening as a result.
What about context?
Components A and B re-render unnecessary. We can prevent it by wrapping Component A with
memo, but first, let’s take a look at the DOM:
React is smart enough to only update DOM where necessary, even in complicated cases like this.
React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
So we know that react render doesn’t mean DOM update. Therefore unnecessary renders do not always lead to expensive DOM manipulations. And in fact, constant re-rendering is one of the core React principles:
However, if you have many calculations inside your React components, they may add up and cause performance issues. That’s why you need to Fix the slow render before you fix the re-render.