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.
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.
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.
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.
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.