ReactDOM.createRoot() in React Js

ReactDOM.createRoot() is a special method in React JS used to optimize your web application’s performance and user experience. It’s particularly useful when you have complex UIs or frequent updates.

Let’s understand with this simple example –

Suppose you have created a complex web application with multiple components, some of which update frequently. for example ‘chat messages’.

Now, use createRoot()  to separate these frequently updated parts of your application and render them simultaneously.

This way, even if one part of your app is slow to update, it won’t block updates to other parts, resulting in a more responsive user interface.

What is ReactDOM.createRoot()?

ReactDOM.createRoot is a popular JavaScript library for creating user interfaces in React JS. It is used for creating and managing the root of a React application.

This method was introduced in React 18 to support the concurrent mode and asynchronous rendering.

  • concurrent mode handles multiple tasks simultaneously to make your app more responsive and improve performance.
  • asynchronous rendering enables asynchronous rendering. React can work on multiple tasks simultaneously for complex UIs and frequent updates to prevent the user interface from freezing or becoming unresponsive during rendering.

Steps to use ReactDOM.createRoot()

Now, let’s see to use ReactDOM.createRoot() with these simple –

1. Import ReactDOM

First, you have to import the  ReactDOM libraries at the beginning of your file.

import ReactDOM from 'react-dom';

2. Create a Root Container

Now, create a root container where your React application will be rendered. This container is mainly an HTML element in your HTML file.

const rootContainer = document.getElementById('root');

3. Create a Root Object

create a root object. This root object is the entry point of your React app. It takes the root container as an argument.

const root = ReactDOM.createRoot(rootContainer);

4. Render Your React Application

Now render a top-level App component of React App that you want to render into the root container.

function App() {
  return <div>Hello, CodingStatus!</div>;
}

root.render(<App />);

5. Updating Your Application:

You can also use the root object to update your application later.

To update your application, you can call the render method again with a new component or an updated component

function UpdatedApp() {
  return <div>Hello, Updated CodingStatus!</div>;
}

root.render(<UpdatedApp />);

ReactDOM.createRoot() Example

When you create a React App you will get some default folders & files. Here we will see the required files to use ReactDOM.createRoot().

1. Create Root Element

index.html is the default file of the React App, in which the root container is defined.This file may have various lines of code but we have mentioned here only required one.

File Name – index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React Example</title>
</head>
<body>
    <div id="root"></div>
    <script src="index.js"></script>
</body>
</html>

2. Create a Component

App.js file is also the default file of React AP with some default lines of code. but here we have updated them with our code to render a simple counter application.

It uses the useState hook to manage the count state, and when the “Increment” button is clicked, it increases the count by 1.

The current count is displayed on the page, and the component structure is defined using JSX.

File Name – App.js

import React, { useState } from 'react';

function App() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h1>Counter</h1>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default App;

3. Create Root Object & Render App

This file index.js is the default file of React App, We have shared this file with the updated code by creating a root object and  rendering the App component into the ‘root’ DOM element.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

const rootContainer = document.getElementById('root');
const root = ReactDOM.createRoot(rootContainer);

root.render(<App />);

4. Update React App

You can also use the root object to update your application asynchronously or when new data becomes available.

For example, you can use setTimeout to update the counter value after a delay

setTimeout(() => {
  const UpdatedApp = () => <div>Updated Count: {count + 1}</div>;
  root.render(<UpdatedApp />);
}, 2000); // Update after a 2-second delay

Suggestion

We’ve shared simple steps with you to use ReactDOM.createRoot() method. Now, you can use and test it yourself.

If you found this tutorial helpful, please share it with your friends so they can learn too