Alex Sidorenko AvatarAlex Sidorenko

14 Sep 2021

A Visual Guide to React Rendering - DOM

It's easy 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's 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 the 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.

Mark Erikson - A (Mostly) Complete Guide to React Rendering Behavior

What about context?

Components A and B re-render unnecessarily. We can prevent this by wrapping Component A with memo, but first, let's take a look at the DOM:

React is smart enough to only update the 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.

React Docs - React Only Updates What鈥檚 Necessary

Performance

So we now know that a React render doesn't necessarily mean a DOM update. Therefore, unnecessary renders do not always lead to expensive DOM manipulations. In fact, constant re-rendering is one of the core React principles:

The slide from one of the first talks about React

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.


Follow me on 饾晱 for short videos about Next.js

饾晱 Follow for more