React

React 18의 createRoot (ReactDOM.render Warning)

citron031 2022. 10. 27. 08:42
  • 리액트 버전 18에 와서 평소처럼 npm run start를 했는데, 다음과 같은 에러 메세지가 콘솔창에 나타났다.

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. Learn more: https://reactjs.org/link/switch-to-createroot

 

How to Upgrade to React 18 – React Blog

As we shared in the release post, React 18 introduces features powered by our new concurrent renderer, with a gradual adoption strategy for existing applications. In this post, we will guide you through the steps for upgrading to React 18. Please report an

reactjs.org

 

  • 새로 나온 리액트 18에서는 ReactDOM.render가 아니라, createRoot를 사용하는 것이 권장된다.
  • 콘솔에 나온 메세지에 따르면, ReactDOM.render는 react 18에서는 더 이상 지원되지 않고 ReactDOM.render를 사용시 react 18이 아니라 react 17로 작동되는 것 같다.
  • 만약 React 18버전으로 프로젝트를 시작하고자 한다면, createRoot를 사용하도록 하자.
  • React 공식문서를 참고하여, 다음과 같이 코드를 바꾸었다.
    🍉 참고한 리액트 공식 문서 : https://ko.reactjs.org/docs/concurrent-mode-reference.html#createroot
 

Concurrent Mode API Reference (Experimental) – React

A JavaScript library for building user interfaces

17.reactjs.org

/*  before  */

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

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

reportWebVitals();
  • 이전의 코드는 이러했지만, react 18부터는 다음과 같이 작성하도록 하자.
/*  after  */

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

const rootNode = document.getElementById('root');

ReactDOM.createRoot(rootNode).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
);

reportWebVitals();
  • ReactDOM의 import가 변경되었고, createRoot(rootNode)가 ReactDOM과 render 사이에 들어가게 되었다.
  • 위와 같이 코드를 고치니, warning 메세지가 없어졌다.

🍲 createRoot를 사용한 React 18에서 StrictMode를 사용하면, react-router-dom v5가 제대로 작동하지 않는 오류가 있을 수 있다.

🥘 따라서, react-router-dom v5를 react 18에서 사용하고자 한다면, StrictMode를 사용하지 않거나, react 18에서는 최신 버전의 react-router-dom를 사용하자.