Virtual DOM is an in-memory object that React maintains to sync UI updates from web app to the browser.
Let's first understand the two prerequisite concepts - Browser's DOM (Document Object Model) and React's Declarative UI Coding
Lets talk about the Browser DOM
DOM (Document Object Model) is a tree representation of the HTML a browser displays on the screen. The browser keeps the UI screen synced to what's in the DOM.
To change something on the UI via JavaScript, we simply modify the DOM. When the browser repaints the UI based on the updated DOM, it may also have to repaint the elements around / below the changed DOM element.
Seemingly simple DOM changes may cause the browser to need a lot of CPU, mem to update the UI. Because DOM changes can require repainting other elements, some DOM changes can trigger repainting hundreds or even thousands of DOM elements (on large pages). Such DOM changes, if triggered repeatedly (eg - via scroll / key-press event listeners), can lead to janky experience or unresponsive pages.
Now, Let's talk about Declarative UI Coding in React
UI coding with React is declarative. Our React code specifies what UI changes need to happen - not how. To update the CalendarForMonth, we update the monthData state value. Accordingly, based on the component's JSX markup,React handles updating the UI. Here, React re-renders CalendarForMonth & it's children components.
Declarative UI code is easier to maintain & scale when creating large & complicated UIs. Our UI code: Ensure state values are updated for various conditions. React Library: Update the UI based on the components JSX and state values.
But, declarative UI code increases the chances of us writing code that causes frequent expensive re-renders. Not having to manage how the UI is updated increases our chances of inadvertently writing code that causes React to frequently re-render a lot of components.
Let's finally talk about Virtual DOM
Virtual DOM is the layer where React first syncs our UI changes. It later syncs Browser DOM with Virtual DOM. Before passing the changes to the Browser DOM, React applies it's own diffing logic to minimize the UI updates that the browser has to perform.
Virtual DOM & diffing are in place to prevent frequent re-renders that can easily happen due to the abstraction of Declarative UI code.
Want to be notified via email when a new explainer is added?
Submit
< of >
Want to be notified when I add a new explainer?
Submit
I create about one or two of these every month (whenever I find time between my webdev work) & you can unsubscribe at any time. 💨
Copyright (c) 2017-2024 Tezify All Rights Reserved. Created in India. GSTIN : 24BBQPS3732P1ZW.