How is React's Virtual DOM faster than DOM? How is React's Virtual DOM faster than DOM? reactjs reactjs

How is React's Virtual DOM faster than DOM?


Changing Virtual DOM should not be much different than changing the real DOM. The problem is in the aftermath: changes in real DOM trigger relayout and repaint, so the less we touch the real thing, the better.

One way to do template rendering is to render the template, then replace the whole container element with newly rendered template. This needs to recalculate everything that just appeared within the container, and everything affected by it. Basically, if the browser was your kitchen and your template container a fridge (and your image of the fridge as it would be in five minutes, your virtual DOM), and you bought a lemon, typical template render would throw out your fridge, imagine what the fridge with a lemon would look like, buy all the ingredients you had before and also a lemon, then fill the new fridge.

The thing that React and other similar frameworks do that speeds this up is the diff process, that finds the minimal set of changes to get the real DOM to reflect the virtual DOM, which can drastically reduce the number of recalculations the browser will need to do in order to paint it. In the previous analogy, you imagine what your fridge would be like after you bought a lemon (fridge with no lemon vs fridge with a lemon), figure out the minimal change (add the lemon) and perform it.

It so happens that throwing out a fridge every time you change anything in it is kind of expensive.

Note that Virtual DOM is not quicker than simply fetching one element via getElementById and changing it. The comparison is between two ways of dealing with changes in complex subtrees, not single elements.