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():
- index.js
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); |
- App.js
Javascript
import './index.css' ; export default function App({ counter }) { return ( <> <h1>neveropen{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():
- index.js
Javascript
import './index.css' ; import { hydrateRoot } from 'react-dom/client' ; import App from './App.js' ; hydrateRoot( document.getElementById( 'root' ), <App /> ); |
- App.js
Javascript
import { useState } from 'react' ; export default function App() { return ( <> <h1>neveropen</h1> <Counter /> </> ); } function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> You clicked me {count} times </button> ); } |
Output: