What is React virtual DOM?


Objectives

Learn how React's virtual DOM improve the efficiency and performance of rendering user interfaces in web applications.

How virtual DOM works?

React's virtual DOM (Document Object Model) is a lightweight representation of the actual HTML DOM. It is an abstraction provided by React to improve the performance and efficiency of rendering user interfaces.

  • Initial rendering: When you create a React component, React builds a virtual DOM tree that mirrors the structure of the actual HTML DOM. This virtual DOM is a plain JavaScript object that contains information about each component and its properties.
  • Updates: When there are changes in the component's state or props, React re-renders the virtual DOM. It then compares the new virtual DOM with the previous one to determine the minimal set of changes required to update the actual HTML DOM.
  • Diffing and reconciliation: React performs a process called "diffing" to identify the differences between the new and previous virtual DOM. It efficiently finds out which parts of the virtual DOM have changed and updates only those parts in the real DOM. This process is known as "reconciliation."

Implementation

Sets up a React root using ReactDOM.createRoot(), associates it with a DOM element with the ID of "root", and renders the App component inside a React.StrictMode.

  • ReactDOM.createRoot(): This function is used to create a new React root and associate it with a specific DOM element in the HTML document.
  • getElementById('root'): This metohd retrieves the DOM element with the ID of "root" from the HTML document.
  • root: This object represents the root of the React component tree that will be rendered into the specified DOM element.
  • root.render(): method is then called to initiate the rendering process.

Tags

React ReactDOM

This post is also on Medium

Source