For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentReact Virtual DOM - Using Virtual DOM in React

React Virtual DOM - Using Virtual DOM in React

Published
24th Apr, 2024
Views
view count loader
Read it in
8 Mins
In this article
    React Virtual DOM - Using Virtual DOM in React

    In this article, we are going to take a deep dive into understanding React JS Virtual DOM, why it is important as a react developer, how it works and look at an example explaining React JS virtual DOM. Click here to know more about usereducer in React. 

    We first need to understand what DOM stands for before proceeding to the main topic. DOM stands for “Document Object Model” which is essentially the UI of an application. The DOM is responsible for serving you changes done in your application. So whenever one hears or talks of manipulating the DOM, they are talking about making changes to the DOM elements. One thing to note is that manipulating the DOM can be slow. How do we solve this issue? Read up to know why Virtual DOM was put to place in the React JS learning path and how it solves our issue.

    JavaScript DOM

    Source: W3School

    What is Virtual DOM and How Does Virtual DOM Works?

    Simply put, the virtual DOM is a representation of a DOM object. In React JS, every DOM element has a corresponding Virtual DOM Object. No doubt that the virtual DOM has the same properties as we have in the normal DOM object but unlike the DOM object where we can directly change what is on the screen, we cannot do that for the virtual DOM.

    The Virtual DOM representation

    Source: Medium

    How the Virtual DOM Works? 

    For every update done on the Virtual DOM, React compares the Virtual DOM with a snapshot of the initial state before the update was done. So, with the help of this comparison done by react js, it automatically figures out which part of your react component needs to be updated. Interestingly, React uses what we call the diffing algorithm to do this and the process of using this diffing algorithm is called diffing. So once reacts compares, it then updates the components which need to be updated with the updated nodes. Let us look at a sample code to see what it looks like:

    Initial DOM State:

    <div>
             <div>
                   <h1>Hello World</h1>
             </div>
             <div>
                   <h1>Hello Universe</h1>
             </div>
    </div>

    Update DOM State:

    <div>
             <div>
                   <h1>Hello World</h1>
             </div>
             <div>
                   <h1>Hello Planet</h1>
             </div>
    </div>

    When the DOM receives an update, it changes only the content of the DOM as we can find in the second block of code. This update is so fast that we don’t usually know when this happens. It only marks the component which needs to be updated and updates it for us.

    How is Virtual DOM Faster? 

    The answer to this question can also be found on how the virtual DOM works. Since there is no direct access or change to the DOM elements in Virtual DOM, that alone makes it extremely fast. Also react only look at the DOM elements which need to be updated and then carry out the update for it instead of re-rendering all elements and decreasing throughput and making updates to components slow.

    Pros and Cons of Virtual DOM 

    It is clear that the performance provided by the Virtual DOM is amazing. Not only that, below are some advantages of the Virtual DOM:

    1. Speed and performance boost
    2. Lightweight
    3. It is simple and clear
    4. Amazing diffing algorithm
    5. It can be used on other frameworks not just react

    Well, anything which has an advantage will have a disadvantage too, let us consider the drawbacks of virtual DOM:

    1. Higher memory usage problems as the diffing algorithms need to keep comparing the elements to know which components needs to be updated or changed.
    2. It is not easily integrated into many other frameworks.
    3. You can’t use it or target template engines.

    Even at the cons mentioned above, virtual DOM is always the go-to because of the boost in performance and speed it offers.

    How Does React JS Make Use of Virtual DOM? 

    Now that we have understood what Virtual DOM is, the pros and cons, and how it is very fast and boosts performance, let us explore how it is being utilized by React JS itself.

    In React JS applications, each UI section is known as a component and each component has a state. So, react js listens to state by what we call the observable pattern. When the state changes, React JS updates the virtual DOM tree. When this virtual DOM tree has been updated, React JS compares the old and current DOM by the diffing process we talked about earlier on. Then once this virtual DOM changes, React then updates only those objects in the real DOM. You can see how performance is optimized.  

    All you need to bear in mind while these operations are handled by React JS itself under the hood. No developer who is using React for production does the logic of updating the virtual DOM themselves. You just have to render the component which is needed and React handles the update for you.  All that is needed from your end is to update the states of your UI components and React takes care of the rest of the business logic which involves updating the DOM for you. Fascinating, isn’t it?

    Why Do Frameworks Make Use of the Virtual DOM? 

    We can take in all the cons of the virtual DOM as a reason why many frameworks use the virtual DOM. But for repetition for emphasis, we will have it listed below with additional reasons why many frameworks adopt the use of virtual DOM.

    1. Boosts Performance.
    2. Very fast in DOM update.
    3. Allows you to write declarative contents.
    4. Simple and less complexity is involved.
    5. Light weighted.
    6. Helps keep your UI clean and updates on the required component in your application.
    7. Compile-time change optimization.
    8. Easy change detection

    To summarize, any advantages of virtual DOM could be regarded also to why many frameworks adopt the use of virtual DOM in their project.

    Enroll for any web development online course here: Web Development Certification Online.  

    How to Mount a HTML Element to Virtual DOM 

    To mount HTML elements to the virtual DOM, we need to create our components and then render it to the root directory of our application. This means that React JS makes use of what we call the JSX syntax for creating components. So, we will use JSX which is combination of JavaScript and XML to create our very first component and then render it to the virtual DOM.

    1. First let us create a simple react app using the “npx command”. So run this code on your terminal “npx create-react-app virtual-dom-demo” to scaffold a react app.

    2. Once the React installation is done, open the react app on your favorite text editor and create a new file called Sample.jsx.  

    3. Enter the below code in the Sample.jsx file:

    const Sample = () => {
          return (
               <h1>Hello World</h1>
            )
    }

    export default Sample;

    React App - Sample.jsx

    4. We have created our first component! How do we mount it to the virtual DOM? Well, all you must do is open your App.js file and import it then render it as you can see in the image below.

    5. Yippie!! You have succeeded in rendering your element to the virtual DOM and any changes made to the component would reflect immediately.

    Mounting HTML Element in Virtual DOM

    Note that you can become a full React JS expert by investing in a comprehensive course like the Knowledgehut React JS Learning Path.

    What Have We Learnt So Far? 

    We have seen what the DOM means on its own and how it operates. We have also learnt about the Virtual DOM and its meaning. We saw that the virtual DOM is an abstract UI which updates just a component we want to update. We also learnt about the pros and cons of using the virtual DOM of which we learnt that the virtual DOM is fast, performance is optimized. We also discussed on how React JS uses virtual DOM under the hood, why React Js frameworks adopt the use of the virtual DOM and lastly, how to mount your first component on the virtual DOM. I’d advise that you reread this to fully see why use the virtual DOM.  

    Master the art of coding with Python - the language that powers the digital world! Join our online certification course for Python and unlock endless possibilities in software development. Start your journey today!

    Conclusion

    The Virtual DOM is not going anywhere as many libraries, frameworks and tools has adopted the use of this virtual DOM to provide performance boost in the services their tools provide. It provides a really nice way of separating all your application’s logic from and helps you rest on the need to manipulate the DOM. You just must write your business logic and it handles the DOM update for you.  

    The approach used by Angular, which is arguably the framework that popularized the concept of Single Page Applications, is called Dirty Model Checking. It’s worth mentioning that dirty model checking, and virtual DOM are not mutually exclusive. They both came as solutions for the same problem but tackling it in different ways. A MVC framework could very well implement both techniques.  

    Like we said earlier, the virtual DOM is not limited to the React ecosystem, we also have the angular virtual Dom, Vue virtual Dom alongside the react JavaScript virtual dom.  

    I hope this article has enlightened you on the virtual Dom essentials and how and why it came to be. Have fun reading and exploring the Dom verse.

    Frequently Asked Questions (FAQs)

    1Is the Shadow DOM the same as the Virtual DOM?

    You can put simply that they are not the same. How do we know that? Even though the shadow DOM and virtual DOM creates a separate instance of the object model, the virtual DOM copies the entire objects while the shadow DOM copies and creates small pieces of the DOM object which is isolated from the object element they copied.

    2Why do we need the Virtual DOM?

    We need the virtual DOM to increase work throughput, to maximize speed of DOM operations, for easy change detection and to keep our UI and logic clean.

    3How many virtual DOMS does React maintain?

    React JS uses just one virtual DOM for operation.

    4How is virtual DOM more efficient than dirty checking?

    You get to know which state is changing easily, you also keep UI and logic clean as well. Virtual DOM saves you the stress and time of checking DOM elements from time to time since everything is done for you under the hood.

    5Which frameworks has the virtual DOM?
    • React JS – React Virtual DOM
    • Vue JS – Vue Virtual DOM
    • Angular JS – Angular Virtual DOM
    • Elm
    • Ember JS
    • Next JS
    • Nuxt JS
    • Svelte
    Profile

    Sachin Bhatnagar

    Blog Author

    Sachin Bhatnagar is an experienced education professional with 20+ years of expertise in Media & Entertainment and Web Technologies. Currently, as the Program Director - Full-Stack at KnowledgeHut, he excels in curriculum development, hands-on training, and strategic deployment of industry-centric educational programs. His online training programs on have attracted over 25,000 learners since 2014. He actively contributes to the development of full-stack training products, leveraging KnowledgeHut's advanced learning platform. Collaborating with organizational leaders, he ensures the success of these programs and has created several technology programs prominently featured in KnowledgeHut's course offerings.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon