프론트엔드 첫걸음

성능개선 - lazy import 본문

개발 공부/React

성능개선 - lazy import

차정 2022. 9. 28. 17:18

 리액트로 개발된 페이지는 기본적으로 SPA ~ 하나의 js ~ 처음 로딩 느림 
로딩이 오래걸리는 페이지는 lazy import 하면 필요할때 import되어 처음 로딩속도를 줄일 수 있음

const OtherComponent = React.lazy(() => import('./OtherComponent'));

lazy 임포트 된 컴포넌트는 별도의 js 파일로 발행됨
lazy 임포트 된 컴포넌트 로딩 시 보여줄 UI를 Suspense로 설정할 수 있음 

import React, { Suspense } from 'react';

const OtherComponent = React.lazy(() => import('./OtherComponent'));

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

 

https://ko.reactjs.org/docs/code-splitting.html