How does React update the DOM?
rwparrish
Posted on November 28, 2020
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.
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!
Posted on November 28, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.