If you have recently upgraded your react version to 18 or initialized an application using create react app, you would have seen the following warning in the browser console:
Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17.
In this article, we will see why this warning appears and how to fix it.
React has recently released version 18.
In the latest version, it has introduced createRoot
API, which is used to support new React features.
createRoot
API will replace the ReactDOM.render
, which was present in the previous versions. Hence we are getting a warning.
You can see what needs to be updated in the diff below:
1import React from "react";2- import ReactDOM from "react-dom";3+ import { createRoot } from "react-dom/client";4import "./index.css";5import App from "./App";6import reportWebVitals from "./reportWebVitals";78+ const container = document.getElementById("root");9+ const root = createRoot(container);1011- ReactDOM.render(12- <React.StrictMode>13- <App />14- </React.StrictMode>,15- document.getElementById("root")16- );1718+ root.render(19+ <React.StrictMode>20+ <App />21+ </React.StrictMode>22+ );2324// If you want to start measuring performance in your app, pass a function25// to log results (for example: reportWebVitals(console.log))26// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals27reportWebVitals();
The updated code will be:
1import React from "react"2import { createRoot } from "react-dom/client"3import "./index.css"4import App from "./App"5import reportWebVitals from "./reportWebVitals"67const container = document.getElementById("root")8const root = createRoot(container)910root.render(11 <React.StrictMode>12 <App />13 </React.StrictMode>14)1516// If you want to start measuring performance in your app, pass a function17// to log results (for example: reportWebVitals(console.log))18// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals19reportWebVitals()
Now if you reload the page, you should not see the warning in the console.
Do follow me on twitter where I post developer insights more often!
Leave a Comment