In React, rendering means converting React elements (written in JSX or plain JavaScript) into actual HTML elements on the webpage. This process is done efficiently using the Virtual DOM, so only the parts that change are updated in the real DOM.
In React 18+, rendering is controlled mainly using ReactDOM.createRoot() and root.render() from the react-dom/client library.
<div id="root">) where your entire React app lives.ReactDOM.createRoot() is used in React 18+ to create a root container. It tells React where in the HTML document the UI should be rendered.
// Create a root container in React 18+
const root = ReactDOM.createRoot(document.getElementById("root"));
Here, "root" refers to the <div id="root"></div> element in your main index.html file. This is the entry point where React will control the UI.
<!-- Root element in index.html -->
<div id="root"></div>
Once the root container is created, the root.render() method is used to render React elements or components into that root.
// Rendering a simple element
root.render(<h1>Hello, React Rendering!</h1>);
// Rendering a component
root.render(<App />);
Whenever the data changes, React recalculates what the UI should look like and updates only the changed parts of the real DOM. This makes React apps smooth and efficient, without full page reloads.
Below is a typical index.js file in a React 18 project that uses ReactDOM.createRoot() and root.render() to display the App component.
// index.js - Entry point of a React app
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
// Create a root container using the <div id="root">
const root = ReactDOM.createRoot(document.getElementById("root"));
// Render the App component inside React.StrictMode
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
ReactDOM.createRoot(...) connects React to the DOM element with id="root".root.render(...) tells React what to show inside that root (here, the <App /> component).<React.StrictMode> helps you catch potential problems early during development.App component.ReactDOM.render().id="root").<React.StrictMode> for better debugging and warnings in development.<div id="root"> element actually exists in your index.html file.root.render() can render a single element, multiple elements, or entire component trees.create-react-app or Vite).index.js (or main.jsx) file in the src folder.<h1> element.Message that returns <p>React is updating this efficiently!</p> and render it inside root.render() along with App.Goal: Understand clearly how ReactDOM.createRoot() and root.render() work together to display and update React components efficiently inside the browser.