본문 바로가기

리액트

ReactDOM.render & ReactDOM.createRoot

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

// New root API
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<App/>)

 

차이가 뭘까?

state나 props 변화가 있을 때,

Legacy API는 변수 container가 변경되지 않더라도 계속 렌더링할 때 container를 전달해야 한다.

import * as ReactDOM from 'react-dom';
import App from 'App';

const container = document.getElementById('app');

// Initial render.
ReactDOM.render(<App tab="home" />, container);

// During an update, React would access
// the root of the DOM element.
ReactDOM.render(<App tab="profile" />, container);

 

그에 반면, 새로운 root API는 데이터 구조의 최상위 레벨에 있는 container를 전달하지 않아도 된다.

import * as ReactDOM from 'react-dom';
import App from 'App';

const container = document.getElementById('app');

// Create a root.
const root = ReactDOM.createRoot(container);

// Initial render: Render an element to the root.
root.render(<App tab="home" />);

// During an update, there's no need to pass the container again.
root.render(<App tab="profile" />);

 

2021.07.27

webpack can't find ReactDOM.createRoot()  에러가 발생했다.

원인 : 현재 React version은 17인데 createRoot()를 사용하려면 version 18부터 가능하다.

해결 : npm install react@alpha react-dom@alpha --force  여기서 force flag의 의미는 둘 다 최신 버전으로 업데이트해준다.

 

참고: https://github.com/reactwg/react-18/discussions/5

 

Replacing render with createRoot · Discussion #5 · reactwg/react-18

Overview React 18 ships two root APIs, which we call the Legacy Root API and the New Root API. Legacy root API: This is the existing API called with ReactDOM.render. This creates a root running in ...

github.com

https://blog.bitsrc.io/trying-out-react-18-alpha-release-bad9aed12bee

 

'리액트' 카테고리의 다른 글

ref로 HTML Element 접근/제어  (0) 2021.08.10
Invalid Hook Call Warning  (0) 2021.07.28
Set up Airbnb Style  (0) 2021.07.05
Lazy Loading  (0) 2021.06.29
개발 환경 설정  (0) 2021.06.21