React.lazy나 Loadable Components를 사용하면 간편하게 코드 분할을 할 수 있다.
React.lazy
React.lazy: 컴포넌트를 렌더링 하는 시점에 비동기적으로 로딩할 수 있게 해주는 유틸함수
Suspense: 리액트 내장 컴포넌트, 코드 분할된 컴포넌트를 로딩하도록 할 수 있고, 로딩이 끝나지 않았을 때 보여줄 UI를 설정할 수 있다.
import React, {useState, Suspense} from 'react';
const SayHi = React.lazy(() => import('./sayHi'));
const App = () => {
const [visible, setVisible] = useState(false);
const onClick = () => {
setVisible(true);
};
return (
<div>
<p onClick={onClick}>Hi</p>
<Suspense fallback={<div>loading..</div>}>
{visible && <SayHi/>}
</Suspense>
</div>
)
};
export default App;
Suspense의 fallback은 로딩이 끝나지 않았을 때 보여줄 ui다.
네트워크에 청크 파일이 생성되는 것을 볼 수 있다.
Loadable Components
Loadable Components는 코드 분할을 편하게 하도록 도와주는 서드파티 라이브러리다.
가장 큰 특징은 서버 사이드 렌더링을 지원한다.
렌더링 하기 전에 필요할 때 분할된 파일을 미리 불러올 수 있는 기능도 있다.
npm install @loadable/component
# or use yarn
yarn add @loadable/component
import React, {useState, Suspense} from 'react';
import loadable from '@loadable/component';
const SayHi = loadable(() => import("./sayHi"), {
fallback: <div>loading...</div>,
});
const App = () => {
const [visible, setVisible] = useState(false);
const onClick = () => {
setVisible(true);
};
const onMouseOver = () => {
SayHi.preload();
};
return (
<div>
<p onClick={onClick} onMouseOver={onMouseOver}>Hi</p>
{visible && <SayHi/>}
</div>
)
};
export default App;
preload()를 사용한 코드를 보면 마우스 커서를 Hi 위에 올리면 로딩이 시작되고,
클릭하면 렌더링된다.