How React updates DOM

The render() method that is called (in class-based components) does not update the content to real DOM or to the JSX in the return statement of functional components. The name here can be misleading. render does not mean that it should render, but that we think of it as a suggestion for how the final result will look like. Let’s look at two important cases:

  • There are no changes in some parts of the final web page, but the render method is called, which is unnecessary in this case.
  • Some props may change, but we do not want to show them on our webpage. So, render will again be unnecessary.

In such cases, we might use shouldComponentUpdate() in class-based components or React.memo in the function-based component. But what happens when we do not use these? Will it re-render every time if there are changes in props that are not used for UI or if the parent component renders it?

No, it will not.

Virtual DOM

When render is called or suggested, it compares virtual DOMs. It will have the old virtual DOM and re-rendered virtual DOM. React takes this approach because it is faster. Here, the re-rendered virtual DOM will be created when the render method is called.

Once the comparison is made, and if any differences are found, then React will update the real DOM and note that it doesn’t re-render the entire DOM. Suppose the text on the button is changed. Then, it won’t re-render the whole button; instead, only the text is changed. It does not touch the real DOM if there aren’t any differences.

As you know, it is expensive to access the real DOMthis is something you want to do as little as possible. Because React has the virtual DOM, the real DOM is touched only if it is necessary.

Free Resources