React 18

React 18

Render your code in React 18

I have previously worked with React 17 on one of my projects, and from now on I am going to work with React 18. So, let's see how to make sure, everything is correct for the code to work.

To install react 18, write this in the terminal:

npm install react@18.0.0 react-dom@18.0.0

Rendering in React 17:

import React from "react"
import ReactDOM from "react-dom"
import App from "./App"

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

Now, in React 18, the initialization method has changed and so has the import. We need to import the client-side version of React-dom, by doing:

import ReactDOM from 'react-dom/client'

This is due to the existence of a server-side version of the code. And the initialization is now done in two steps:

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<App />)

or one, if you render it in a single line:

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

Rendering in React 18:

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

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<App />)

or

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

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

This is the main change in React 18 besides 17 and the entire application code remains the same.

Thank you so much for reading. For more such blogs, follow HerCodeShots .

Reference:
https://javascript.plainenglish.io/react-18-what-you-need-to-know-d7bed3216e2e