DEV Community

Cover image for How the React updates DOM?
Kedar Kodgire
Kedar Kodgire

Posted on

How the React updates DOM?

So, how does the react update real DOM i.e. in the browser?

The render() method which is being called(in class-based components) doesn't update the content to real DOM and neither the JSX in the return statement of functional components. The name here can be misleading render doesn't mean that it should render, but 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 being called, which is unnecessary in this case.
  • Some props may change but we don't want to show it on our webpage. so render will be unnecessary again.

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 rerender every time if there are changes in props which are not used for UI or if the parent component renders it? NO It will not.

And here comes VIRTUAL DOM into the picture

So, when the render is called/suggested it compares virtual DOM's. It will have Old Virtual DOM and re-rendered Virtual DOM. React takes this approach because it's faster. Here 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 rerender the entire DOM. Suppose, the text on the button is changed then it won't rerender the whole button instead only text is changed. And it doesn't touch is real DOM if there aren't any differences.

icons which represent virtual DOM's and real DOM with the connection between them

This technique is awesome, isn't it? As you know accessing the real DOM is expensive (Why is it?) and this is something you wanna do as little as possible. As react has this virtual DOM idea the real DOM is touched only if it's necessary.

Hope you enjoyed this post,
Happy learning.

--

Further reads

Top comments (2)

Collapse
 
ppezaris profile image
ppezaris

As your app gets larger, you really do need to pay attention to componentShouldUpdate and React.memo -- otherwise even the virtual dom render step will make your app feel sluggish. I wish there were more online guides about this.

Collapse
 
sandydamy profile image
Sandesh Damkondwar • Edited

Agree, we will end up in hitting the render method unnecessarily and read DOM & virtual DOM and check diff and decide it will be rendered or not. If the DOM is huge and have lot of nested props usage, one unused prop change might end up in doing lot of unnecessary complex tasks if componentShouldUpdate is not handled correctly.