React render() Method
In React 18,ReactDOM.render the method is ReactDOM.createRoot and root.render replaced. 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 for creating a root object that can control the root component. This method returns a root object that you can use to render your React component tree.
** 2、root.render**
Use the render method of the root object returned from ReactDOM.createRoot 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 the root
const
root
=
ReactDOM.
createRoot
(
rootElement
)
;
// Render the component
root.
render
(
<
App
/>
);
Suppose you have a simple App component; you can render it using createRoot 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 the root
const
root
=
ReactDOM.
createRoot
(
rootElement
)
;
// Render the component
root.
render
(
<
App
/>
);
Online test example
The following example uses render() The method inserts a new entry in the user profile table in the id="root" to render the React element Header in a container:
Example
class
Header
extends
React
.
Component
{
render
(
)
{
return
(
<
h1
Runoob Tutorial - Learning is not just about technology, but also about 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 provides better support for concurrent rendering and other new features.
React 18 introduces concurrent features, making React applications more efficient when handling heavy updates.
React Component Lifecycle