Jillian Keenan
react | frontend-development

The Virtual DOM

Jillian Keenan
bees

If you have previous experience with React, you might have come across the term "virtual DOM" before. You may have even searched for it, read the description, and still found yourself wondering, "But what exactly is the virtual DOM?" Or perhaps you understood it right away, in which case, well done! I certainly didn't.

Let's look at the React team's explanation of what the Virtual DOM is:

"The virtual DOM (VDOM) is a programming concept where an ideal, or 'virtual', representation of a UI is kept in memory and synced with the 'real' DOM by a library such as ReactDOM. This process is called reconciliation."

The virtual DOM allows React to efficiently update and render components by only updating the necessary parts of the actual DOM, resulting in improved performance. But how does it do this?

The DOM and virtual DOM are stored in memory in the structure of a tree. React uses "The Diffing Algorithm" to compare the two. Any nodes that are different get updated; this is known as "reconciliation".

How does the Diffing Algorithm work?

Virtual DOM: React maintains a virtual representation of the DOM and creates a new Virtual DOM tree when data changes.

visual representation of react creating the virtual dom

Element Diffing: React compares the previous Virtual DOM tree with the new one to identify differences.

visual representation of react diffing the previous virtual dom with the current

Minimal & Batched Updates: React generates a minimal set of updates to transform the current DOM to match the new Virtual DOM, instead of updating the entire DOM. React applies updates in a single batch to reduce browser reflows and improve performance.

visual representation of react making minimal and batch updates

Keyed Elements: The use of keys in React components helps accurately track changes in lists, improving efficiency.

visual representation of the virtual dom tree with keys corresponding to nodes

Complexity of the Diffing Algorithm in terms of time and space

The diffing algorithm in React updates the DOM efficiently by performing necessary operations in O(n) time. This significantly reduces computational cost compared to algorithms with a time complexity of O(n³). Which is particularly beneficial for a large number of elements that are being rendered on a page.

Jillian Keenan
made with 💗