The Virtual DOM

By

Published · Updated

Tagged: React

Learn how the Virtual DOM works in React, keeping a copy of the DOM, diffing changes when a component is marked dirty, and batching updates to the real DOM.

Many existing frameworks, before React came on the scene, were directly manipulating the DOM on every change.

First, what is the DOM?

The DOM (Document Object Model) is a Tree representation of the page, starting from the <html> tag, going down into every child, which are called nodes.

It’s kept in the browser memory, and directly linked to what you see in a page. The DOM has an API that you can use to traverse it, access every single node, filter them, modify them.

The API is the familiar syntax you have likely seen many times, if you were not using the abstract API provided by jQuery and friends:

document.getElementById(id)
document.getElementsByTagName(name)
document.createElement(name)
parentNode.appendChild(node)
element.innerHTML
element.style.left
element.setAttribute()
element.getAttribute()
element.addEventListener()
window.onload
window.scrollTo()

React keeps a copy of the DOM representation, for what concerns the React rendering: the Virtual DOM

The Virtual DOM Explained

Every time the DOM changes, the browser has to do two intensive operations: repaint (visual or content changes to an element that do not affect the layout and positioning relative to other elements) and reflow (recalculate the layout of a portion of the page - or the whole page layout).

React uses a Virtual DOM to help the browser use less resources when changes need to be done on a page.

When you call a state setter, like the one you get from useState, with a value different than the previous one, React marks that component as dirty and schedules a re-render. A component also re-renders when its parent re-renders or when a context it reads changes.

What happens next is:

Why is the Virtual DOM helpful: batching

The key thing is that React batches much of the changes and performs a unique update to the real DOM, by changing all the elements that need to be changed at the same time, so the repaint and reflow the browser must perform to render the changes are executed just once.

Since React 18 this batching is automatic everywhere. If you call several state setters in the same event handler, a setTimeout, or after an await, React waits until your code is done and re-renders once:

async function handleClick() {
  const data = await fetchData()
  setLoading(false)
  setItems(data)
  setError(null)
  // one re-render, not three
}

In the rare case you need the DOM updated right away, for example to scroll to an element you just added, wrap the update in flushSync() from react-dom.

How React decides what to change

Comparing two trees node by node would be slow, so React uses a few simple rules when it diffs the old Virtual DOM with the new one:

That last point is why keys matter. With a stable key, React knows the item with key="42" is the same item even after you sort the list or add one at the top:

<ul>
  {todos.map(todo => (
    <li key={todo.id}>{todo.title}</li>
  ))}
</ul>

If you use the array index as the key and then insert an item at the top, every item gets a new index. React thinks each one changed, and state like a typed input or a checkbox can end up attached to the wrong row. Use an ID from your data instead.

You can also use a key on purpose to reset a component. <Chat key={contact.id} contact={contact} /> gives you a fresh Chat, with empty state, every time the contact changes.

One more consequence: never define a component inside another component. Every render creates a new function, so for React it’s a new type, and the inner component loses its state on every render.

React only touches what changed

When the diff finds no difference for a DOM node, React leaves it alone. Take this component, re-rendered every second with a new time:

function Clock({ time }) {
  return (
    <>
      <h1>{time}</h1>
      <input />
    </>
  )
}

React updates the text of the <h1>, and that’s it. The <input> is the same type in the same position, so it’s not recreated, and whatever the user typed in it stays there.

Is the Virtual DOM faster than the real DOM?

Not by itself. Building a Virtual DOM and diffing it is extra work on top of updating the real DOM. The benefit is that you describe what the UI should look like, and React figures out a small set of DOM changes for you, instead of you writing every appendChild() and setAttribute() by hand.

Other frameworks, like Svelte and Solid, don’t use a Virtual DOM at all. They work out at compile time, or through fine-grained reactivity, which DOM nodes to update.

Want to check how well you understand reconciliation and the key prop? Try my free React key quiz.

Want me to talk about your product? You can sponsor this site.

Related posts about react: