The Problem

DOM manipulation is the heart of the modern, interactive web. Unfortunately, it is also slow.

This slowness is made worse by the fact that most popular JavaScript frameworks update the DOM much more than necessary.

For example, let's say that you have a list containing ten items. You check off the first item. Most JavaScript frameworks would rebuild the entire list. That's ten times more work than necessary!

Rebuilding a list is no big deal, but modern websites can use huge amounts of DOM manipulation. Inefficient updating has become a serious problem.

To address this problem, the people at React popularized something called the virtual DOM.

The Virtual DOM

In React, every DOM object gets a corresponding "virtual DOM object." A virtual DOM object is a representation of a DOM object, like a lightweight copy.

A virtual DOM object looks just like a real DOM object, but it lacks the real thing's power to directly change the screen.

Manipulating the DOM is slow, but manipulating the virtual DOM is much faster because the screen is never redrawn. Think of it as editing a blueprint, as opposed to moving rooms in an actual house.

How it helps

Whenever you change and rerender a JSX element, every single virtual DOM object gets rebuilt. That sounds inefficient, but its cost is insignificant because the virtual DOM updates so quickly.

Once the virtual DOM has updated, React compares the upated virtual DOM to a snapshot taken right before the update.

By comparing the new virtual DOM with the pre-update version, React figures out exactly which virtual DOM objects have changed. This process is called "diffing."

Once React knows which virtual DOM objects have changed, then React updates those objects, and only those objects, on the real DOM. In our example from earlier, React would be smart enough to rebuild your one checked-off list-item, and leave the rest of your list alone.

In conclusion, here's what happens whenever you try to update the DOM in React:

  1. The virtual DOM gets updated to reflect the changes that you made.
  2. The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed.
  3. The changed objects, and the changed objects only, get updated on the real DOM.
  4. Changes on the real DOM cause their corresopnding HTML elements to update.

If you'd like to learn more, start here.