React is a library used to create user interfaces declaratively. Learn about React components, they are descriptions of what UIs should look like, and React itself builds and maintains the user interface.
However, React is maintained by Facebook and a group of developers and businesses. React may be used as a basis for creating a single-page web app or mobile apps.
Before Anything else watch this beautiful story of virtual dom. https://www.youtube.com/watch?v=BYbgopx44vo
What is DOM ?
DOM stands for Document Object Model.
When a web page is loaded in the browser (example: Google Chrome, Firefox etc), the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects. It helps define –
- HTML elements as Objects
- Events for HTML elements
- Properties for HTML elements
- Methods for HTML elements
The virtual DOM is only a virtual representation of the DOM. Everytime the state of our application changes, the virtual DOM gets updated instead of the real DOM.
What makes DOM manipulation slow?
The DOM is represented as a tree data structure. Because of that, the changes and updates to the DOM are fast. But after the change, the updated element and it’s children have to be re-rendered to update the application UI. The re-rendering or re-painting of the UI is what makes it slow. Therefore, the more UI components you have, the more expensive the DOM updates could be, since they would need to be re-rendered for every DOM update.
How is Virtual DOM faster?
Once this is done, the virtual DOM calculates the best possible method to make these changes to the real DOM. This ensures that there are minimal operations on the real DOM. Hence, reducing the performance cost of updating the real DOM.
The image below shows the virtual DOM tree and the diffing process.
The red circles represent the nodes that have changed. These nodes represent the UI elements that have had their state changed. The difference between the previous version of the virtual DOM tree and the current virtual DOM tree is then calculated. The whole parent subtree then gets re-rendered to give the updated UI. This updated tree is then batch updated to the real DOM.
How does React use Virtual DOM
Now that you have a fair understanding of what a Virtual DOM is, and how it can help with performance of your app, lets look into how React leverages the virtual DOM.
In React every UI piece is a component, and each component has a state. React follows the observable pattern and listens for state changes. When the state of a component changes, React updates the virtual DOM tree. Once the virtual DOM has been updated, React then compares the current version of the virtual DOM with the previous version of the virtual DOM. This process is called “diffing”.