Web Dev/3. React 관련

React Code splitting with lazy and suspense

hYhY1234 2021. 2. 4. 15:27
728x90

Code Splitting in React

[공식 문서]

 

 

 

React.lazy를 통한 dynamic import

// Before
import SomeComponent from './SomeComponent'

// After

const SomeComponent = React.lazy(() => import('./SomeComponent'))

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <SomeComponent />
      </Suspense>
    </div>
  );
}

 

Lazy를 통해서 실제로 컴포넌트가 렌더링 될때, 동적으로 파일을 import 할 수 있다. 이렇게 나뉜 부분은 번들링이 따로되서 네트워크 탭을 확인하면 다른 js 파일로 load 되는 것을 확인 할 수 있다. 

 

Lazy component 는 항상 Suspense Component 내에서 렌더링 되어야한다. 이를 통해서 loading 중과 같은 fallback 컨텐츠를 보여줄 수 있기 때문이다. 이 Suspense Component 는 lazy component 위라면 어디든지 넣어도 된다. 

 

Route를 기반으로 code splitting 하는 기법이 많이 사용되지만 컴포넌트를 기반으로도 code splitting을 할 수 있다. 하지만 적어도 30 kb 정도는 되야 code splitting 하는 의미가 있다고 한다.