Alex Sidorenko

A Visual Guide to React Rendering - DOM

September 14, 2021

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?

The tree of React components. When root component renders, entire subtree re-renders

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.

Devtools result of above mentioned component. The only thing that re-renders is a text node containing count

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.

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

What about context?

The tree of React components. The root component passes the context value to a deeply nested component. The entire subtree re-renders

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:

The tree of React components. The root component passes the context value to a deeply nested component. The entire subtree re-renders

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.

React Docs - React Only Updates What’s Necessary

Performance

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:

The slide from one of the first talks about React
Pete Hunt: React: Rethinking best practices - JSConf EU (2013)

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.

Want to get better at modern React?

Subscribe to get one short article delivered to your inbox every week

One article a week. No spam.
Unsubscribe any time