Learnitweb

Difference Between react and react-dom

react

  • Contains the core functionality for building React components and managing component lifecycle.
  • Provides tools for creating components (React.createElement, React.Component, etc.) and managing their state and rendering.
  • It is primarily concerned with the logic of React components, but does not handle rendering to the browser or DOM.

react-dom

  • Handles the rendering of React components to the DOM (Document Object Model) in the browser.
  • Provides the ReactDOM.render method to attach React components to the DOM, enabling the React app to render on the page.
  • It also provides methods for manipulating the DOM when state changes occur.

Why react-dom is separated from react

  1. Separation of Concerns:
    • React’s core functionality (like component creation and state management) can be independent of the rendering logic. By separating the rendering logic (react-dom), it allows React to be used in environments other than the browser, such as React Native (which renders to native mobile components) or React 360 (for virtual reality), where the rendering logic is different but the core React principles remain the same.
  2. Platform Independence:
    • By separating react and react-dom, React enables platform-specific packages. For example, react-native is a platform-specific version of React for mobile devices that does not need to rely on react-dom. This makes React more flexible and adaptable to various environments (like web browsers, native mobile apps, or even server-side rendering with react-dom/server).
  3. Smaller Bundle Sizes:
    • When react and react-dom are separate, you only need to include react-dom in your browser code, but you could potentially use React without the DOM when building applications for other environments. This separation helps to reduce unnecessary dependencies and optimize the application bundle size for web apps.
  4. Different Rendering Targets:
    • As React evolves, the rendering targets could vary. For example, with the introduction of React Server Components, the rendering logic for servers and browsers differs. Having react-dom separate from react allows React’s core to remain platform-agnostic, while react-dom can evolve independently for browser-specific use cases.

Example:

import React from 'react'; // Core React for components
import ReactDOM from 'react-dom'; // React DOM for rendering to the browser

function App() {
  return <h1>Hello, world!</h1>;
}

ReactDOM.render(<App />, document.getElementById('root'));
  • React is used to define the App component.
  • ReactDOM is used to render the component to the DOM in the browser.

Conclusion

  • react contains the core logic of React, while react-dom is specifically for rendering components in the browser.
  • This separation improves flexibility, enabling React to run in multiple environments and optimizing the app bundle.