How many times have you heard your developer colleagues screaming …. “React is fast but it often makes development slower”?
5, 10, 100 or maybe 1000 times! Right?
Well, I am not joking or ranting about the framework. I am here to tell you the TRUTH.
The truth that most developers found hard to AGREE upon.
The truth about DOM you need to know about
For an instance, let’s say you have an E-commerce application that showcases a list of ten items. You checked-off the first item and find out that the list has been REBUILT. Now, that’s 10 TIMES more work than necessary!
The Engineers at React found out a way to address this problem. They came up with something which is called as “Virtual DOM”.
Enters the Virtual DOM - React
In React, for every DOM, you have a corresponding object of VIRTUAL DOM which resembles like a lightweight copy of the original DOM object. Both DOM object and Virtual DOM object have similar properties with a smaller difference of capitalizing what to update.
Once the Virtual DOM gets updated by rendering the UI components, React compares the virtual DOM with a virtual DOM snapshot that was taken right before the update.
In this way, React evaluates which VIRTUAL DOM objects have changed. This process is called as “diffing”.
In the above example, React would be smart enough to analyze the changes and rebuild the first item thereby leaving aside the rest of the list alone.
This gives React a big SPEED Boost as React only updates the necessary parts of the DOM.
The DIRTY Parts about React’s Virtual DOM
Whenever you call setState on a React component, React will mark it as dirty. At the time of ending event loop, React will look at these dirty components and re-render them. This happens exactly ONE time when the DOM is being updated.
Upon calling of SetState, React rebuilds the virtual DOM for all the child components. But the problem would be if you re-render root element, you will end up rendering the whole app which is hard to optimize.
Thankfully, there are TONS of optimization techniques that can make your React app faster. There is this definitive guide on making a React app FASTER which goes into details on optimizing the React components.