Methods for initializing an app on the client are provided by the react-dom/client package. The majority of your components shouldn't require the use of this module.
Install the required package:
Client-specific initialization techniques are available in the react-dom/client package. The majority of your components shouldn't require the use of this module.
import * as ReactDOM from 'react-dom/client';
If you use ES5 with npm, you can write:
createRoot(container[, options]);
Used in client environments:
- createRoot()
- hydrateRoot()
ReactJS createRoot and hydrateRoot are two functions in the React JavaScript library used for creating and hydrating a root React component.
Creating React Project:
Step 1: To create a react app, install react modules through the npm command.
npm create-react-app project name
Step 2: After creating your react project, move into the folder to perform different operations.
cd project name
Step 3: After creating the ReactJS application, import the following dependencies into your app.
import * as ReactDOM from 'react-dom/client'; // ES6
createRoot(container[, options]); // ES5 with npm
Project Structure: The project structure should look like below:
1. createRoot(): createRoot is used to create a root React component that acts as the container for the whole React application. It sets up the necessary context and provides the root component with access to the React DOM.
syntax-
createRoot(container[, options]);
Return the root after creating a React root for the given container. A React element can be rendered into the DOM using the root and render
const root = createRoot(container);
root.render(element)
createRoot accepts two options:
- onRecoverableError: An optional callback that is activated when React fixes faults on its own.
- identifierPrefix: A prefix that Reacts can use to prefix ids produced by React.useId. When using numerous roots on the same page, it is helpful to avoid conflicts. The prefix must match what the server is using.
The root can also be unmounted with unmount:
root.unmount();
Note: The container node you pass createRoot() has control over the contents. When render is invoked, any existing DOM components inside are replaced. For effective updates, later calls employ React's DOM diffing mechanism.
The container node is not changed by createRoot() (only modifies the children of the container). An existing DOM node may be able to have a component added to it without having its children changed.
It is not supported to hydrate a server-rendered container using createRoot(). Instead, use hydrateRoot().
Example: Below example will demonstrate the use of createRoot():
JavaScript
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.js';
const root = createRoot(document.getElementById('root'));
let i = 0;
setInterval(() => {
root.render(<App counter={i} />);
i++;
}, 500);
JavaScript
import './index.css';
export default function App({ counter }) {
return (
<>
<h1>GeeksforGeeks{counter}</h1>
<input placeholder="Type something here" />
</>
);
}
Output:
2. hydrateRoot(): hydrateRoot is used to hydrate a server-side rendered React application on the client. It takes the markup generated by the server and updates it with the necessary event handlers and state so that the application behaves correctly on the client. This allows for a smoother, faster initial load for the user and improved search engine optimization (SEO).
syntax -
hydrateRoot(container, element[, options])
Same as createRoot(), but is used to hydrate a container whose HTML contents were rendered by ReactDOMServer. React will attempt to attach event listeners to the existing markup.
hydrateRoot accepts two options:
- onRecoverableError: An optional callback that is activated when React fixes faults on its own.
- identifierPrefix: a choice prefix React uses react-generated ids. useId. When using numerous roots on the same page, it is helpful to avoid conflicts. The prefix must match what the server is using.
Note: React expects that the rendered content on the client and server will be the same. It can cover up text content variances, but you should treat inconsistencies as bugs and correct them. React issues a caution regarding incompatibilities during hydration when in development mode. If there are mismatches, there is no assurance that attribute differences will be fixed. Due to the low frequency of incompatibilities in most apps and the prohibitively high cost of checking all markup, this is crucial for efficiency.
Example: The below example will illustrate the use of hydrateRoot():
JavaScript
import './index.css';
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(
document.getElementById('root'),
<App />
);
JavaScript
import { useState } from 'react';
export default function App() {
return (
<>
<h1>GeeksforGeeks</h1>
<Counter />
</>
);
}
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
You clicked me {count} times
</button>
);
}
Output:
Similar Reads
ReactJS Examples
This article contains a wide collection of React JS examples. These examples are categorized based on the topics, including components, props, hooks, and advanced topics in React. Many of these program examples contain multiple approaches to solve the respective problems.These React JS examples prov
5 min read
React Components
In React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS constructor() Method
In React, lifecycle methods help control what happens at different stages of a component's life. The constructor() method is one of the first methods called when a class component is created. It is mainly used to set up the initial state and bind event handlers before the component appears on the sc
4 min read
React vs React Dom
React is a JavaScript library used for building user interfaces, especially for single-page applications. React DOM is a separate package that enables React to update and render UI components on the web browser by directly interacting with the browser's Document Object Model (DOM), ensuring smooth,
4 min read
ReactJS Server Components
React is a JavaScript library which is used to develop frontend of websites. Since it's introduction in the year 2013 React has gained a lot of popularity among the web developers around the world. The library has a great support from the community and is evolving at a high speed from its launch. In
3 min read
ReactJS isDOMComponent() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use isDOMComponent() method. This
2 min read
ReactJS Portals
React portals come up with a way to render children into a DOM node that occurs outside the DOM hierarchy of the parent component. The portals were introduced in React 16.0 version.So far we were having one DOM element in the HTML into which we were mounting our react application, i.e., the root ele
5 min read
ReactJS bind() Method
The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component. Syntax:this.function.bind(this,[arg1...]);Parameter:It accepts two parameters, the first parameter is thethis: keyword used for binding [arg1...]: the sequence of argumen
2 min read
React Lifecycle
In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Events
In React, events are actions that occur within an application, such as clicking a button, typing in a text field, or moving the mouse. React provides an efficient way to handle these actions using its event system. Event handlers like onClick, onChange, and onSubmit are used to capture and respond t
8 min read