DEV Community

Cover image for How does React update the DOM?
rwparrish
rwparrish

Posted on • Updated on

How does React update the DOM?

As I continue learning about React and working my way through this series on React, I find myself falling in love with it. In this blog, I would like to touch on React's virtual DOM.

What is the DOM?

According to MDN, the Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.
...
The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.

React's Virtual DOM

React uses virtual DOM(s). A virtual DOM simply is a DOM representation in Javascript.

The render() method does not immediately render to the real DOM.

Render is in fact, more a suggestion of what the HTML should look like, but render() can very well be called and be the same as what was already displayed.

Upon render() being called, React compares virtual DOMs. It has an old virtual DOM and a re-rendered or a future virtual DOM. By comparing the "old" VDOM with the "future" VDOM, React can determine if there are any differences. If it detects differences, it reaches out to the real DOM and updates it--but not entirely!--it only changes the real DOM in the places where differences were detected.

Alt Text

This is important because as you might know, accessing the DOM is really slow. Specifically, every time the DOM changes, the browser needs to recalculate the CSS, layout, and repaint the page. This takes time and is something you want to do as little as possible.

Recap

React's virtual DOM means speed in most cases and it helps alleviate us from having to think about when to render changes to the DOM and focus more on writing code creatively and solving problems.

Happy Coding!

Top comments (4)

Collapse
 
shadowtime2000 profile image
shadowtime2000

I would avoid stating that using a vdom simply makes it faster, because it doesn't always make it faster. It is always based around the implementation of the vdom and how it exactly scales with more components.

Collapse
 
rwparrish profile image
rwparrish

Thank you for taking the time to give me feedback! I will correct this!

Collapse
 
shriji profile image
Shriji

A virtual DOM simply is a DOM representation in Javascript. It is much faster than the real DOM

This claim is false. Check out the blog here svelte.dev/blog/virtual-dom-is-pur...

The future of javascript frameworks will be compiler frameworks.

Collapse
 
rwparrish profile image
rwparrish • Edited

Thanks for the feedback and the link. That was an interesting read. The point about "diffing" is something I haven't thought about yet but it makes a lot of sense.