How React.JS works under the hood

Sanidhya Pawar
2 min readMar 31, 2021

Have you ever wondered when you add a comment to your favourite post on instagram, does that load the whole page after updating the database and the backend microservice? Answer to this is yes, if plain HTML/CSS is used, but we can avoid this inefficient approach if we are dividing the whole user screen into multiple components. So even if one of the component, lets say comment related component is updated, only changes are made to that particular DOM elements and not to all the other elements. Also, this will refresh only the comment component to get the latest info from the backend, instead of refreshing the complete user page. So how exactly does React.JS overcomes this inefficiency? The answer to this is the virtual DOM. DOM creation and update are a slower process. To speed up the process, ReactJS uses the concept of virtual DOM which makes the loading faster. A virtual DOM is just a lightweight javascript object which is just the copy of a real DOM.

Virtual DOM works in the following 3 steps:-

  1. Whenever any prop or state change occurs, the entire component is re-rendered in the virtual DOM. This can be avoided using the hooks like useEffect, this can basically avoid re-rendering the entire component when a specific prop or the state is changed.
  2. Then the difference between the real DOM and the virtual DOM is calculated using the diffing algorithm.
  3. After the final evaluations, the real DOM will only be updated with those elements which have actually changed and not the whole DOM tree.

This was an abstract explanation of how React.JS works, we will discuss about this in more detail in a separate discussion. But this is how React.JS achieves the superiority over its peers.

Happy Learning!

--

--