π§ What is ReactDOM?
ReactDOM
is the glue between React components and the browser's DOM. It allows React to render, update, and manage components within the HTML document.
It's a package that's typically imported alongside react
and used in your main entry point file (index.js
or main.jsx
).
π Rendering Components to the DOM
The most commonly used method in ReactDOM
is ReactDOM.render()
. Itβs used to render a React element or component into a specific DOM node.
jsx
import React from 'react';
import ReactDOM from 'react-dom';
const element = <h1>Hello, world!</h1>;
ReactDOM.render(element, document.getElementById('root'));
- The first argument is the React element or component.
- The second argument is the target DOM element (
#root
in most React apps).
Note: In React 18+, ReactDOM.render()
has been replaced with createRoot()
from react-dom/client
.
π§° Other ReactDOM Methods
Here are some other useful methods provided by ReactDOM
:
β
ReactDOM.createRoot()
Modern way to render in React 18+:
jsx
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
π ReactDOM.hydrate()
Used for server-side rendering (SSR) to attach event listeners to server-rendered HTML.
β ReactDOM.unmountComponentAtNode(node)
Removes a mounted component from the DOM.
π ReactDOM.findDOMNode(component)
Returns the underlying DOM node for a mounted class component. (Not recommended in modern React with function components and refs.)
π Virtual DOM Efficiency
ReactDOM works with Reactβs virtual DOM, which is a lightweight copy of the actual DOM:
- React makes updates to the virtual DOM.
- It compares (diffs) the current vs. previous virtual DOM.
- Then, ReactDOM updates only the changed parts of the real DOM β this improves performance and efficiency.
π Summary
- ReactDOM is essential for rendering React components into the browser DOM.
- It handles updates efficiently through the virtual DOM.
- In React 18+, prefer
createRoot()
over render()
. - Other features include hydration, unmounting, and accessing DOM nodes.