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.
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.
<!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.
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()`.
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);React 18 Concurrent Mode
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.
function tick() {
const element = (
<h2>It is {new Date().toLocaleTimeString()}.</h2>
);
root.render(element); // Assume root is defined
}
setInterval(tick, 1000);React Only Updates What's Necessary
In practice, most React apps call `root.render()` once. UI updates are handled by components managing state.
- Read about the Virtual DOM and Reconciliation process.
- Explore Server-Side Rendering (SSR) with React.
- Understand how Next.js handles rendering (Server Components, Client Components).
- "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?"