Purpose and Usage of react-dom Package
The react-dom
package is a critical part of the React ecosystem that handles the rendering of React components to the DOM (Document Object Model). While react
itself is responsible for creating components, react-dom
connects those components to the browser or another environment.
Purpose:
- Rendering UI to the Browser:
react-dom
provides methods that render React elements into actual DOM nodes. - Managing Updates: It efficiently updates and synchronizes the DOM when the underlying React components change.
- Portal Support: It allows rendering components outside of the main DOM hierarchy using portals.
- Hydration for Server-Side Rendering (SSR):
react-dom
handles hydration of server-rendered markup on the client side.
Common Usage:
-
Rendering a React App:
import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />);
Here,
ReactDOM.createRoot
creates a root to render theApp
component inside the HTML element with id"root"
. -
Using Portals:
import ReactDOM from 'react-dom'; ReactDOM.createPortal( <div>Popup Content</div>, document.getElementById('modal-root') );
This allows you to render components outside of the normal parent-child hierarchy (useful for modals, tooltips, etc.).
-
Hydration (Server-Side Rendering):
import ReactDOM from 'react-dom/client'; const root = ReactDOM.hydrateRoot(document.getElementById('root'), <App />);
Hydration attaches event listeners and makes a server-rendered app interactive without re-rendering the whole UI.
Key Methods in react-dom
:
Method | Purpose |
---|---|
createRoot | Create a root for concurrent rendering (React 18+). |
render | (Deprecated in React 18) Renders a React element into the DOM. |
hydrateRoot | Hydrate a server-rendered application. |
createPortal | Render children into a DOM node outside the parent component hierarchy. |