Disadvantages of virtual DOM

ReactJs is a widely used Ui library, And if you are reading this post so it is confirmed you have thought about something different. Different than the normal reader. Or probably you have read about the advantages of virtual DOM.

Let’s back to the main topic, Is it possible to have some disadvantages of virtual DOM. Probably yes in some scenarios. then what could be that scenario.

Before jumping to the scenarios, Let’s understand how virtual DOM works. So when we write the react components, actually we prepare the Data for the react library. That (data) react library process and consume and then it returns some new output (DOM).

So Process and Consume means it(React) has to do some work in order to consume the data, that is where disadvantages of virtual dom will come into the picture.

What it does to process the data/components. Well react has to go over each of the components and call it with the props and take the output of the components and create a kind of elements/fiber tree. And then it matches with the older one.

So whenever we update the state, React has to create a new tree and it matches against the older one.

Now let’s suppose this tree is too big to let’s say one million elements into it. Now in order to add one class into the element or if you want to enter text into the input element. This whole tree will be created even though it has to update the single element.

There are a lot of events in the DOM that triggers in very short intervals.

  1. When a user enters text into the input
  2. Some updates based on the setInteval of 10ms
  3. Mouse event
  4. scroll event

A lot is there.

So all and all every time something will be changed even though it is a small change, React has to do a lot of work. That work is the disadvantage of virtual DOM.

Absolutely there are some solutions to this problem, even though react has to go over each component. Even if the change is done in one component’s internal state, React will process each component’s corresponding fiber.

And yes fiber is one of the implementations that React has made due to the time limit for the processing of the virtual DOM. React has to process everything into the 16ms if work is not done in that time interval, React will pose and let the UI update/do its work. and It resumes back to process the fibers. It does so to avoid the jerky effects in the browser.

So if you want to avoid a lot of processing every time you update the state, you should provide the pre-processed data to the React components. Some of the processing could be done on the API layer instead of doing inside the component.

If the processing of the component data is dependent on the UI we should use the React.memo to prevent un-needed proccessing.


More on the Disadvantages of Virtual DOM




Leave a comment

Your email address will not be published. Required fields are marked *