CodeNewbie Community 🌱

aagya11
aagya11

Posted on

Understanding Virtual DOM in React

Virtual DOM is one of the key features of React library. It is the central feature that allows React to be so fast and efficient. Considering that its speed and efficiency is why React is so popular, you could say that Virtual DOM is one of the features that allows React to dominate front-end development right now.

What is Virtual DOM?

This feature is easiest to understand in context of real DOM, which is a JavaScript representation of all HTML elements on a page. Virtual DOM is like a shadow copy of the real DOM, which has a number of advantages: it allows React to keep track of internal app data (called state) and efficiently update the real DOM by settling the differences between real and virtual DOMs.

Contrary to what you might think, all React components actually render virtual DOM. When component re-renders, it is re-rendering the virtual DOM. Behind the scenes, React does its magic to settle differences between virtual and real DOM as efficiently as possible.

You probably know that changes to component’s state or their props trigger the component and all of its children to re-render. This often happens when you access values from text input field in React. At first, this may seem like an inefficient process, but it’s necessary to make sure React apps always stay up to date and display latest changes. Even without users having to refresh the page.

This approach would indeed be inefficient without virtual DOM. Because virtual DOM is just a shadow copy, it’s much lighter to work with, so React can perform re-render operations for entire branches of web application and still keep the process efficient.
Actual rendering of real DOM elements happens after the fact. When React notices that virtual and real DOMs are different, it updates the real DOM to reflect latest changes from the virtual DOM.

What is the render method?

Render is a very special method in React. Updating the page to show latest data is only possible thanks to render method. All React components must have a render() method. In case of class components, the method is explicitly defined and returns component layout written in JSX. In case of functional components, the component itself plays the role of render() method and returns JSX code.

By default, the render method has only one return statement to define the component layout. However, this is not always the case. You can call other functions or methods inside the render() method. These will be executed every time the component renders (when it mounts as well as when it updates). Effectively, it’s a way to replicate the way componentDidUpdate lifecycle method or useEffect() hook works.

If you want to perform a side-effect only once, then componentDidMount() or useEffect() without a dependency array is your best bet.

Button to trigger re-render of virtual DOM

Sometimes you want a button to dynamically change the component’s appearance. Let’s take ‘dark mode’ as an example. Dark mode is a common feature for web apps and one that users love a lot.

In React, the easy way to implement dark mode is to create a state variable (or a property in the state) to hold a boolean value. And use conditional styling or conditional classNames to change the element’s appearance depending on the state value. This article explores string interpolation, a useful feature for dynamic styling in React.

This is less difficult than it sounds. JSX allows you to embed dynamic expressions in the component layout. className, which is React’s way of setting normal class, can have a dynamic class value that is determined by a condition.

For example, if your dark mode status (whether it is turned on or off) is stored in dark state variable (or state property), you can implement a ternary operator that returns className value depending on current value of the state variable.

Let’s look at an example:

..

As you can see, JSX code looks almost identical to HTML. The only difference is that you can include JavaScript expressions in your code. We use curly braces to embed dynamic expressions inside JSX. In this example, the value for className attribute will be dynamic.
Ternary operator checks if the condition (before the question mark) is true. If it is, then ternary operator returns the first value that comes after the question mark. It can be a string, a Boolean, or even an expression. If it is false, then it returns second value after the semicolon. Similarly, you can use any type of value here. Sometimes you might even need to return another ternary operator, to handle multiple scenarios (sort of similar to if/else statements inside JSX).

Speaking of, you can only use inline expressions in JSX. You can not use statements (like if statement or for loop) that require multiple lines of code. For this reason, ternary operators and for-loop alternatives (like map() and filter() JavaScript methods) are your good friends in JSX.

Ternary operators can also help you implement dynamic styles in React. Just like className values, you can use curly braces to set dynamic values for styles in React. Like everything else in JSX, styles are also JavaScript. They are represented as JavaScript objects, where property is the CSS property and values are CSS values.

Embedding dynamic expressions even allows you to render elements and components based on some condition. For example, if a certain state value is true, then render some element or a component. This is often used in conditional collapse / expand feature in React.

Summary

In this article, we discussed Virtual DOM its importance for building web applications with React. Understanding Virtual DOM means understanding React, and behind the scenes decisions that make this library work. We also went over important rendering features that developers often use. Conditional rendering, as well as conditional styling are important aspects of web application building with React.

Top comments (3)

Collapse
 
mrboos123d profile image
mrboos123d

Introducing the McDonald's Menu UK Prices – your gateway to delicious, budget-friendly choices. Explore an array of wallet-friendly options without compromising on taste. Discover great value at McDonald’s today!

Collapse
 
derckedshaw2 profile image
goharshah002

Hey, foodies enjoy the delicious flavors on the Sonic Menu With Prices! The best things from Sonic are a wide range of tasty options from classic to new creations. Find your perfect meal today! Our diverse range of menu are designed to satisfy your craving.

Collapse
 
viviandsena profile image
viviandsena

Feel free to personalize these or combine words to create a unique name for your Private Story Names!