Uhmm Virtual DOM In React?...
Tags: webdev, javascript, frontend, react
Published: 2024-05-23 02:27:15


<h1>Introduction to the Virtual DOM</h1>

React was finally introduced to us the past two days and one of the topics that triggered my interest was the the virtual DOM. Well... based on my understanding, the virtual DOM is a brilliant technique that was invented to simplify the pain point of manually updating the actual DOM when a component's state or props change. It acts as an additional hidden layer that is very lightweight and can improve the performance of a web application. So meaning that everytime a component's state or props change, the virtual DOM will get re-rendered. It is important to understand that not the entire virtual DOM will re-render from scratch, but just the nodes that have changed will be updated. It is oOnly after the completion of the virtual DOM updates, the actual DOM also gets updated.

So it actually makes sense to say that it is one of the most helpful features in developing UI using React is its ability to use a virtual DOM. This is because it is a lightweight JavaScript object which is a copy of the actual DOM. The creation of the virtual DOM is a one-time activity in the React context. Whenever a component's state changes, a new virtual DOM can be re-created. Under the hood it is said that React implements a reconciliation algorithm to help ensure the UI gets updated. It will compare the current and old state of a virtual DOM and based on the output, it will decide which nodes need to be re-rendered in the actual DOM.

 
<h1>Ever wondered on how it works?</h1>


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w28yabgzycew11qrmhv8.jpg)

It came to my realization that it can be quite expensive to manipulate the DOM for every small thing. If we can solve as many changes as possible off of the real DOM, then we can minimize changes. Therefore, using a virtual DOM, we can decide that only a small part of the page has changed and tell React to only update parts that we care about. Besides improvement of efficiency in terms of reducing the frequency and area for actual manipulation in the real DOM with minimal updates, utilizing the concept of virtual DOM also allows the React application to track changes to components even if just part of the data changes.

The virtual DOM (VDOM) is a programming concept where an ideal, or "virtual", representation of a UI is kept in memory and synced with the "real" DOM by a library such as React. This process is called reconciliation. In React, for every VDOM, there is a corresponding "real" parent VDOM that connects the tree to the root of the actual rendered HTML landscape. For a UI with a tree structure, we normally use a tree to describe all elements and their relationships. Each element is a node in the tree and the tree instantiation recursively adds to this further node instances, describing the relation between the child and parent nodes.


<h1>Consistent User Experience(Benefits of Virtual DOM)</h1>


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kt15tynqg8o38ndquqqm.jpg)

I further learned about some of the benefits that come with using JavaScript. I’m assume that all my seniors in react development or those yet starting like myself use or at least have heard of a couple of JavaScript frameworks, and among them being Angular, Ember, Backbone, etc. Well we all know by now that React is popular for a couple of reasons like it’s simple to understand and use, plays well with different frameworks, it’s fast, and the one very big point is that it uses Virtual DOM. Other frameworks use the regular DOM model. They make changes directly into the DOM like adding a couple of nodes here or removing a couple of nodes there. Because of that, there are some problems and React solves all of these using the Virtual DOM. Let’s discuss these in detail in the next couple of minutes. First and important point: Optimization. With the normal DOM, it leads to re-flow and re-paint for every modification that happens in the DOM. 

<h3>Wonder where I read that?</h3>

If you read Steve’s article (scrolling performance), you would understand that we should avoid re-flow and re-paint to make the scrolling performance good. And it might lead to performance issues. Well not with Virtual DOM, as React will write all those changes to the Virtual DOM first and then will do the re-flow and re-paint at the end. So making more changes will not affect your application and the user can interact with the page without any lag. That is, your application looks faster. It’s one of the important parts in providing a good user experience to the user.


<h1> Benefits of Virtual DOM in React</h1> 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9v2xghth7kih9nwroebk.png)

Working with a Virtual DOM allows React to do a lot of cool stuff. With the help of currently available hardware, React can optimize and balance the different parts of a system like rendering, preserving state, and making the app still responsive. It's not just working with the Virtual DOM. The Virtual DOM is the way to make all components work in harmony.

This is a system a developer can use to know what has changed and what needs to be modified in the actual DOM. React uses efficient heuristics to decide what changed in the Virtual DOM and it's able to update the actual DOM the best way. React makes sure the impact of updating the actual DOM is minimal and keeps it synchronized with the latest version of Virtual DOM. This feature is the key part of the conversation "React is fast".
React uses the object pooler pattern to use memory that is allocated for components efficiently. This render-to-Virtual DOM compared with updating the actual DOM means React is increasing the performance of rendering and the user experience of your app.

React is fast. While rendering and performing an update, it only works with Virtual DOM. **It never updates the actual DOM directly.** This concept is similar to double buffering in window systems or computer graphics. Updating the Virtual DOM is a much cheaper operation than updating the actual DOM. This optimization helps developers to build complex, feature-rich and heavy apps.

<h1>Creating a virtual DOM element:</h1>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jii91dntj7ymrsmj73sg.jpg)



```
jsx const parentDiv = React.createElement('div', { id: 'parentDiv' },
       [ React.createElement('h1', null, 'A title'), 
           React.createElement('p', null, 'Some content') 
         ]
            );
```

This helps us to maintain the markup and the JavaScript in different files and it makes it easy for us to maintain the JavaScript files and markup. This is a very small example of a virtual DOM created using React. We just need to remember that whenever we need to make a dynamic representation of the contents, we need to do it using a render method and return the virtual DOM element from it.

For the above code, the equivalent JavaScript node structure will be:

export default App; In this example, the render method gets called when the component gets created. We return the virtual DOM element from it. The HTML structure which we see in the form of JSX gets converted into a function and that function creates the equivalent JavaScript node structure of the DOM_ (M. Mohammad El-Basioni & M. Abd El-Kader, 2024) or Virtual DOM.

Now that we have the environment ready, let’s create a virtual DOM element using React. Take a look at this example snippet where we create a virtual DOM element using React.



```
import React from 'react';

class App extends React.Component{ render(){ 

    return( 

    <div id="parentDiv"> 
    <h1>A title</h1> 
    <p>Some dynamic content</p> 
    </div> 
  );
 } 
}
```

(Barsocchi et al., 2021)

<h4> Using JSX?</h4>

In the first case, the virtual representation of the real DOM model is created and then assigned to the real DOM. Initially, when the page is loaded and elements are being created, React starts from the root and creates the entire virtual DOM. (Jain et al., 2019) (Olarotimi Badru et al., 2023) 

When the logic in the constructor changes the virtual DOM, React first applies the changes to the virtual elements and then searches for differences between the old and the new elements, and then it finally applies these changes to the real elements (Crijan 2020) (Jain et al., 2019). 

Armed with the basic knowledge of JSX and VDOM, let’s proceed with some code examples (L. Sega et al., 2022). I will not delve into the details of React or its components at this stage. This shouldn’t bother you much – with a snippet you don’t need to understand the entire system to see how the basic principles work. Below are code snippets in both JS/TS and JSX that depict working with React components, loops, JS operations and errors. Note that JSX snippets can be saved in .jsx or .tsx files (an optional syntax extension that can be used as a placeholder within JS).

**Example Demonstrated in code snippet**

React comprises of different components and states associated with these components which reflect updates on the system. React’s component can be considered as part or extent of the DOM Tree. In case any component is changed then it impacts the resultant representation of the rendered tree. Within this phase, a representation (either a mapping or transpilation) is produced and used inside a renderer like a browser, via an HTML generation step or any kind of Visual DOM building. (https://react.universome.io/html/virtual-dom). 

For coping with the large amount of rendered elements, React has adopted a concept of Virtual DOM. Through this Virtual DOM, React identifies the DOM elements associated with its components and during the execution, whenever update operation is performed, so React compares these changes with the resultant Virtual DOM if there are any changes then indeed these will be taken over to the real DOM. This concept/technique enhances the overall system performance. 

(https://react.universome.io/html/introduction). (Barsocchi et al., 2021) An example of how Virtual DOM works on React is shown below: 


```
import React from 'react'
import Employee from './Employee'

// employee component 

function Employee() { 

const emp = { 
name: 'Peter', company: 'United Innovations', 
salary: 1500 }; 

return ( 

<div> 
<p>Emp name: {emp.name}</p> 
<p>Emp company: {emp.company}</p> 
<p>Emp salary: {emp.salary}</p> 
</div> ); 

} ReactDOM.render( 

<div> 
<h2>Welcome to the revealcoding.com refer to employee details.</h2> 

<Employee/> 

</div>, document.getElementById('root')); 
```

In the above example, content is initially is inside html representation. When user enters the url, at server side this code is converted/suggested to the client in the virtual DOM representation in the form of Babel that is when at client side, it calls the Javascript file at that time calling the ReactDOM.render function which would/evaluate the virtual DOM since, it would/evaluate virtual DOM into DOM representation.



<h1>Updating a virtual DOM</h1>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/id4cmfo4gjdp3xyzwhwy.png)

Take the following example, to update the virtual DOM we don’t have to explicitly manipulate it ourselves because react automatically does this for us, react sees how the actual DOM looks now and compares it with a snapshot of the actual DOM that it took just before in the form of virtual DOM, afterward react applies all the necessary changes to the actual DOM to make it look like the virtual DOM, suppose a virtual DOM which is just a pattern of the actual DOM. If there is any changes in state or props, react will rebuild UI, but it does not necessarily mean that it will changes the whole actual DOM, it might only change a small part or add new items to the list. If you to work with virtual DOM, directly in react, then I have realized that one can make use of react-reconciliation, fortunately there is a library for that  that being react-reconciliation (L. Sega et al., 2022).

React's virtual DOM is a lightweight copy of the actual DOM. To use React, we don’t need to directly manipulate the virtual DOM which is a good thing because, we know that any direct manipulation with real DOM can affect page performance, but sometimes we want our UI to update due to some update in state or props, so to update the UI, we have to update the virtual DOM earlier when react detects, any changes in virtual DOM, it updates the actual DOM accordingly, so in this article we will see, how to update this virtual DOM with the example set below (Bai, 2022).

<h2>Advanced Techniques for Updating Virtual DOM in JavaScript</h2>

  **Code Snippets for Updating Virtual DOM**

The below snippet shows the component receiving new messages as props in every subsequent update. These messages are then rendered as a list of components – just like in a real-world chat application. On further mocking a chat application (after certain intervals), the new list of ChatMessage components is created. **Like for instance:**

```
export default ChatWindow; 

   const ChatWindow = (props) => ( 
   <div className="chat-window"> 
   <div className="messages"> 
     {props.messages.map((message, index) => { 
   return <ChatMessage message={message} 
      key={index} />; })} 
   </div> 
   </div> );

import './ChatWindow.css'; 
import ChatMessage from './ChatMessage';
jsx import React from 'react';
```


**Look at the source code for the 'ChatWindow' component:**

In the above example, we have a 'ChatWindow' component. The message list of the ChatWindow is immutable which means it cannot be manipulated once created. This is to make sure that the message list cannot be directly mutated; rather, the new message list is created after every update.

Additionally, for every message list update (every new message display in the chat application), a new ChatWindow component is created to replace the old one.

<h1>How do I conclude?</h1>


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7x5rjlt6ydytlo8w829v.jpg)



Well if you have read till this far please leave your like and most importantly your comments on what you think you love about the article or where I can do best to improve. This really matters to me as I am also learning react. Thank you!