React’s Virtual DOM

As a React developer, there are a few questions your interviewer is guaranteed to ask. One of them is, “Can you tell me about the Virtual DOM and why it’s important in React?” (to which you’ll say “Of course!” and continue with a brief summary of what you will learn or get a refresher on by reading this post).

The first bit of information you should definitely know is that it is distinct from the DOM, or document object model. The DOM represents the UI of an application, and its structure is like a tree comprised of nodes for each HTML element. It can be modified directly using JavaScript. For example, you’ve probably seen a bit of code written like this: document.getElementById('id-of-element').innerHTML = "new text". This function would update the DOM, the CSS and layout would be recalculated, and the page would re-render and display the “new text”.

On a mass scale, directly updating the DOM can be pretty costly in terms of performance. This is why React uses the more lightweight virtual DOM to quickly update the page any time a change happens. The virtual DOM exists as two copies of the real DOM. When a change is detected, the copy of the virtual DOM that holds the changes is compared with the original, unchanged copy so that React can trigger a change in the real DOM. The difference between this process (called ‘diffing’) and direct manipulation of the real DOM is that only the pieces that have changed are re-rendered, as opposed to the entire page.

Although React developers don’t need to program updates to the real DOM and simply need to make sure that state is updated at the appropriate times, it’s still good to know why React is so great in the first place. After all, if you don’t understand and appreciate the value of the tools you use on a daily basis, why be a dev in the first place? πŸ™‚

Leave a Reply

Create your own website, free on WordPress.com.Create your own website.
Start free