How does ReactJS update the DOM?

Sami C.
2 min readApr 26, 2019

--

Before we delve into the react part, let’s first talk about what the DOM really is. A lot of people struggle to get their head around what the DOM actually does.

What is the DOM?

The Document Object Model is a cross-platform and language-independent application programming interface that treats an HTML, XHTML, or XML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document with a logical tree

In essence DOM is:

The html of a web page represented as a tree structure.

The easiest way to do DOM manipulation would be to re-render the whole web page if something has changed. Obviously this would be really bad towards performance. Keep in mind that DOM manipulation is slow, The reason being that the DOM manipulation itself is actually fast, It’s a simple operation, but it’s the re-rendering and re-calculating of the CSS that the browser has to do that makes it slow. Manipulate as little as possible is the goal. Luckily react uses something called Virtual DOM.

What is Virtual DOM?

Virtual DOM is basically the whole HTML DOM represented in JavaScript.

Now that we have our DOM in JavaScript, things get interesting.

There’s 3 steps that react takes to handle the changes in DOM:

  1. React creates the virtual DOM a second time before any changes.
  2. If a change occurs, the second virtual DOM gets adjusted and is now compared against the first virtual DOM.
  3. If any changes are detected, it creates a difference between these two virtual DOMS, the difference is then applied onto the real DOM.

The benefit is that only the difference got applied onto the real DOM and re-rendered.

Thanks for reading and hopefully this helps some of you!

Happy coding!

--

--

Sami C.
Sami C.

Written by Sami C.

Freelance Software Engineer

No responses yet