React Render HTML
How React displays HTML elements and interacts with the DOM.

React's primary function is to render HTML to a web page. It achieves this by creating and managing its own representation of the DOM, known as the Virtual DOM. When you write React components, you are essentially describing what the HTML output should look like.

The Root DOM Node

Typically, in a traditional HTML file that uses React, there is a single root DOM node. This is usually a <div> element where your entire React application will be mounted.

html
<!DOCTYPE html>
<html>
<body>
  <div id="root"></div> <!-- Root DOM node -->
</body>
</html>

In modern React applications built with frameworks like Next.js or tools like Vite, this `index.html` file and the root node setup are often handled for you.

Rendering Elements

React elements are the smallest building blocks. To render an element into a root DOM node, you use `ReactDOM.createRoot()` (React 18+) followed by `root.render()`.

javascript
import ReactDOM from 'react-dom/client';

const domNode = document.getElementById('root');
const root = ReactDOM.createRoot(domNode);
const elementToRender = <h1>Hello from React!</h1>;
root.render(elementToRender);
Updating the Rendered Element

React elements are immutable. To update the UI, create a new element and pass it to `root.render()`. React efficiently updates only what's necessary.

javascript
function tick() {
const element = (
  <h2>It is {new Date().toLocaleTimeString()}.</h2>
);
root.render(element); // Assume root is defined
}
setInterval(tick, 1000);

In practice, most React apps call `root.render()` once. UI updates are handled by components managing state.

Dive Deeper into Rendering
Practice Zone

Test Your Knowledge

Ace the Interview
  • "What is the Virtual DOM and how does it help React's performance?"
  • "Explain the role of `ReactDOM.createRoot()` and `root.render()` in a React application."
  • "Are React elements mutable or immutable? How does this affect UI updates?"
  • "If you call `root.render()` multiple times with slightly different elements, what does React do?"