React render() Method

React 组件生命周期React Component Lifecycle

In React 18,ReactDOM.renderthe method wasReactDOM.createRootandroot.renderreplaced. The new API provides more powerful features and better performance. The following is an introduction to these methods and how to use them.

1、ReactDOM.createRoot

ReactDOM.createRoot is a new method introduced in React 18, used to create a root object that can control the root component. This method returns a root object, which you can use to render your React component tree.

2、root.render

Use the render method of the root object returned by the ReactDOM.createRoot method to render the component tree. This approach replaces the old ReactDOM.render method.

Example

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App'; // Your main component

// Get the root element
const rootElement = document.getElementById('root');

// Create root
const root = ReactDOM.createRoot(rootElement);

// Render component
root.render(<App />);

Suppose you have a simple App component, you can use createRoot to render it like this:

Example

// App.js
import React from 'react';

function App() {
  return (
    <div>
      <h1>Hello, React 18!</h1>
    </div>
  );
}

export default App;

Example

// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

// Get the root element
const rootElement = document.getElementById('root');

// Create root
const root = ReactDOM.createRoot(rootElement);

// Render component
root.render(<App />);

Online Example

The following example uses therender()method inid="root"to render React elements in the container ofHeader:

Example

class Header extends React.Component { render() { return ( <h1>Example Tutorial - What you learn is not only technology, but also dreams!</h1> ); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<Header />, document.getElementById('root'));

Try it »

In React 17 and earlier versions, you would use the ReactDOM.render method to render components:

Example

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

In React 18, using createRoot can better support concurrent rendering and other new features.

React 18 introduces concurrent features, making React applications more efficient when handling heavy updates.

React 组件生命周期React Component Lifecycle

Other Extensions