Virtual DOM

  • Virtual DOM is a lightweight, in-memory representation of the real DOM which is synced with the real DOM by a library such as ReactDOM.
  • DOM manipulation is quite slow when compared to other operations in JavaScript, hence concept of virtual DOM was created.
  • Example: Consider a list that is being rendered inside the DOM. If one of the items in the list changes, the entire list gets rendered again instead of just rendering the item that was changed/updated. This is called inefficient updating.
  • React uses two virtual DOMs to render the user interface:
    • One of them is used to store the current state of the objects
    • Other one to store the previous state of the objects.

Working

  • When changes are made to the state of a React component, the virtual DOM is updated instead of the real DOM.
  • React then compares the virtual DOM with a snapshot of the virtual DOM taken right before the update, a process known as reconciliation
  • It identifies the differences (diffing algorithm) and only updates the necessary parts of the real DOM.
  • This minimizes direct manipulation of the real DOM, which is slow, and results in significant performance improvements.

Virtual_DOM