What is Virtual Dom? | What is JSX ? | Components in Reactjs
How React Works?
Before starting to work with React JS, let's understand how a React project works.
React js is a powerful JavaScript library for building user interfaces, primarily focusing on efficient rendering and maintaining the state of components.
What is JSX?
- React code is written in JSX, which stands for JavaScript XML.
- JSX is a JavaScript syntax extension that enables writing HTML-like code within JavaScript
- This makes it easier for developers to create and manage UI elements because it closely resembles HTML.
- JSX simplifies the process by providing a more readable and expressive syntax.
- For an example, take a look at this code:
1import React from 'react';
2import ReactDOM from 'react-dom';
3
4function App() {
5 return (
6 <div>
7 <h1>Hello, world!</h1>
8 <p>Welcome to my React app.</p>
9 </div>
10 );
11}
12
13ReactDOM.render(<App />, document.getElementById('root'));
What is Virtual DOM?
- In traditional JavaScript, developers manipulate the Document Object Model (DOM) to create and update elements dynamically.
- This process can be slow and inefficient, especially for complex applications with many UI updates.
- React introduces the concept of a Virtual DOM to enhance performance.
- The Virtual DOM is an efficient, in-memory model of the real DOM.
- When a component's state changes, React updates the Virtual DOM first.
- It then compares the new Virtual DOM with the previous version to identify the changes. This process is known as "reconciliation.
How the Virtual DOM Works
Initial Render
- React generates a Virtual DOM structure that mirrors the component tree.
- ReactDOM renders this representation to the actual DOM.
State Change
When the state changes , React creates a new Virtual DOM representation of the component tree.
Reconciliation
- React performs a comparison between the current Virtual DOM and the previous version to detect changes, a process called "reconciliation."
- React then determines the smallest set of updates required to reflect those changes in the actual DOM.
DOM Update
- React efficiently updates only the specific parts of the actual DOM that have been modified.
- This minimizes direct DOM manipulations, resulting in better performance.
DOM manipulation vs Virtual DOM
Let's compare traditional DOM manipulation with Virtual DOM using an example.
Example of Traditional DOM Manipulation
Here's an example of how you might implement a simple counter with traditional JavaScript DOM manipulation
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Traditional JS Counter</title>
7</head>
8<body>
9 <div id="app">
10 <p id="counter">You clicked 0 times</p>
11 <button id="increment-btn">Click me</button>
12 </div>
13
14 <script>
15 let count = 0;
16 const counterElement = document.getElementById('counter');
17 const button = document.getElementById('increment-btn');
18
19 button.addEventListener('click', () => {
20 count++;
21 counterElement.textContent = `You clicked ${count} times`;
22 });
23 </script>
24</body>
25</html>
- The DOM is directly manipulated by selecting elements and updating their content.
- Each time the button is clicked, the textContent of the counterElement is updated.
Example of Virtual DOM
- Let's look at a React example that demonstrates how the Virtual DOM works, using a simple counter application.
- This example will illustrate the process from initial render to state updates and reconciliation.
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>React Virtual DOM Example</title>
7</head>
8<body>
9 <div id="root"></div>
10 <script src="https://unpkg.com/react/umd/react.development.js"></script>
11 <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
12 <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
13 <script type="text/babel">
14
15 const { useState } = React;
16
17 function Counter() {
18 // Initial state
19 const [count, setCount] = useState(0);
20
21 return (
22 <div>
23 <p>You clicked {count} times</p>
24 <button onClick={() => setCount(count + 1)}>Click me</button>
25 </div>
26 );
27 }
28
29 ReactDOM.render(<Counter />, document.getElementById('root'));
30
31 </script>
32</body>
33</html>
How This Code Illustrates the Virtual DOM Process Initial Render
- When the Counter component is rendered for the first time, React creates a Virtual DOM representation of the Counter component.
- The Virtual DOM consists of a tree structure that represents the initial state of the UI: <div><p>You clicked 0 times</p><button>Click me</button></div>.
State Change
When the user clicks the button, the onClick event handler updates the state using setCount(count + 1).
This triggers a re-render of the Counter component with the updated state. React creates a new Virtual DOM representation reflecting the updated count.
- Reconciliation
- In this case, only the text inside the <p> element has changed (e.g., from "You clicked 0 times" to "You clicked 1 times").
- React calculates the minimal set of changes needed and updates only the affected parts of the actual DOM.
- DOM Update
- React updates the actual DOM to reflect the new state. Only the <p> element's content is updated with the new count value.
- This minimizes the number of DOM manipulations, resulting in a more efficient update process.
Components in React
- React components are the fundamental building blocks of a React application.
- They enable you to break down the UI into distinct, reusable components.
- React offers two primary types of components: functional components and class components.
How to Create a Component
Creating a React component is simple. Whether it's a functional or class component, both follow a straightforward structure:
- Functional Component
- Define a JavaScript function.
- Return JSX inside the function.
- Pass data using props if necessary.
1function MyComponent(props) {
2 return <div>{props.message}</div>;
3}
Functional Components
- A functional component is a plain JavaScript function that takes in props (properties) as its argument and returns a React element, typically using JSX.
- They are simpler to write and have no internal state management or lifecycle methods before.
- However, with the introduction of React Hooks, functional components can manage state and handle side effects.
Example of a Functional Component
1function Greeting(props) {
2 return <h1>Hello, {props.name}!</h1>;
3}
4
5// Usage
6<Greeting name="Sehaj" />
In this example, the Greeting component is a function that accepts props and renders an h1 tag with a greeting message.
The name prop is passed in when the component is used, making it dynamic.
Class-based Components
- Class-based components are more powerful in terms of functionality.
- They allow state management and have access to lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
- Before the introduction of hooks, class components were the only way to manage local component state and handle component lifecycle events.
- Class components extend React.Component and must implement a render() method that returns the JSX to be rendered.
Example of a Class-based Component:
1class Welcome extends React.Component {
2 render() {
3 return <h1>Welcome, {this.props.name}!</h1>;
4 }
5}
6
7// Usage
8<Welcome name="Sehaj" />
Here, the Welcome class extends React.Component and defines a render method that uses this.props.name to display the user's name.
If you need more further detailed explanation of class and Functional Components then Do check this Video below:
Conclusion
- The Virtual DOM is an efficient, in-memory model of the real DOM.
- JSX is a JavaScript syntax extension that enables writing HTML-like code within JavaScript.
- Efficient: React updates only the changed DOM parts.
- Reusable: Components improve code reuse.
- Simplified: JSX blends HTML with JavaScript.