CodePark/ questions / Rendering & reconciliation
START PRACTICINGPRACTICE
Frontend question · React › Rendering & reconciliation

What is the virtual DOM, and how does React use it to update the page?

The virtual DOM is the tree of plain JavaScript objects, called React elements, that your components return. These objects are cheap to create compared with real DOM nodes.

React updates the page in three steps:

  • Render: when state changes, React calls the affected components again to get a new element tree.
  • Reconciliation: React compares the new tree with the previous one.
  • Commit: React applies only the smallest set of changes to the real DOM.

Reconciliation uses heuristics, simple rules that are fast but not perfect:

  • An element of a different type at the same position is destroyed and rebuilt.
  • An element of the same type is updated in place with new props.
  • key identifies items in lists.

The benefit is not that the DOM is slow in general. The benefit is that you write declarative code, and React works out efficient updates for you.

  • React elements are lightweight JavaScript objects that describe the UI.
  • A re-render produces a new tree, which React compares with the previous one.
  • A different type means remount. The same type means React updates the props.
  • Keys identify list items across renders.
  • The commit applies only the necessary DOM changes.