티스토리 뷰
lazy
`lazy` lets you defer loading component’s code until it is rendered for the first time.
`lazy`가 컴포넌트의 코드를 처음으로 렌더링할 때까지 로딩을 지연시킬 수 있는 기능을 제공한다.
lazy(load)
Call lazy outside your components to declare a lazy-loaded React component:
컴포넌트 외부에서 lazy 호출하여 지연 로드된 React 컴포넌트를 선언한다:
import { lazy } from 'react';
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
// React.Suspense
//
// 위 코드와 같이 lazy를 통해 import를 하면 해당 path로 이동할 때 컴포넌트를 불러오게 된다.
// 이 과정에서 로딩하는 시간이 생기게 되며,
// 로딩되는 시간동안 로딩 화면이 보여지도록 해주는 역할을 하는 것이 바로 Suspense 이다.
Lazy-loading components with Suspense
Usually, you import components with the static import declaration:
대게, 정적 import 선언으로 컴포넌트를 import 해온다.
import MarkdownPreview from './MarkdownPreview.js';
To defer loading this component’s code until it’s rendered for the first time, replace this import with:
이 컴포넌트의 코드가 처음 렌더링될 때까지 로딩을 연기하려면 이 import를 다음으로 대체한다:
import { lazy } from 'react';
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
This code relies on dynamic import(), which might require support from your bundler or framework.
이 코드는 번들러나 프레임 워크의 지원을 필요로 하는 동적 import에 의존한다.
Now that your component’s code loads on demand, you also need to specify what should be displayed while it is loading. You can do this by wrapping the lazy component or any of its parents into a <Suspense> boundary:
이제 컴포넌트의 코드가 요청 시 로드되므로, 로드되는 동안 표시될 내용을 지정해야 한다.
지연 컴포넌트나 그 부모 컴포넌트를 <Suspense>로 감싸면 된다.
<Suspense fallback={<Loading />}>
<h2>Preview</h2>
<MarkdownPreview />
</Suspense>
In this example, the code for MarkdownPreview won’t be loaded until you attempt to render it. If MarkdownPreview hasn’t loaded yet, Loading will be shown in its place. Try ticking the checkbox:
예를 들어, 렌더링을 시도할 떄까지 MarkdownPreview 코드가 로드되지 않는다.
만약 MarkdownPreview가 아직 로드되지 않은 경우, 로딩중이 대신 보여질 것이다. 체크박스를 ticking 해보자.
https://codesandbox.io/s/s49rnf?file=%2FMarkdownPreview.js&utm_medium=sandpack
hardcore-swirles-s49rnf - CodeSandbox
hardcore-swirles-s49rnf using immer, react, react-dom, react-scripts, remarkable
codesandbox.io
This demo loads with an artificial delay. The next time you untick and tick the checkbox, Preview will be cached, so there will be no loading state. To see the loading state again, click “Reset” on the sandbox.
이 데모는 인위적인 지연으로 로드된다.
다음에 확인란을 선택 해제하고 다시 선택하면, 프리뷰가 캐쉬되어 로딩 상태가 표시되지 않는다.
로딩 상태를 다시 보려면, 샌드박스에서 reset을 클릭한다.
Troubleshooting
My lazy component’s state gets reset unexpectedly
지연 컴포넌트의 상태가 예기치 않게 초기화된다.
Do not declare lazy components inside other components:
다른 컴포넌트 내부에서 레이지 컴포넌트를 선언하지 마쇼
import { lazy } from 'react';
function Editor() {
// 🔴 Bad: This will cause all state to be reset on re-renders
// 🔴 Bad: 이렇게 할 경우 재렌더링 시 모든 상태가 초기화된다.
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
// ...
}
Instead, always declare them at the top level of your module:
대신, 항상 모듈의 가장 최상단 레벨에서 선언하세요:
import { lazy } from 'react';
// ✅ Good: Declare lazy components outside of your components
// ✅ Good: 컴포넌트 외부에 지연 컴포넌트 선언하기
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
function Editor() {
// ...
}
정리
동적으로 로딩되는 컴포넌트의 코드를 필요한 시점에 가져오는 역할을 한다.
보통 React에서 모든 컴포넌트의 코드는 처음에 함께 번들로 묶여서 로드되는데, lazy를 사용하면 컴포넌트의 코드를 초기 렌더링 시에 로드하는 것이 아니라, 컴포넌트가 실제로 사용될 때까지 로딩을 지연시킬 수 있다.
실제로 화면에 렌더링되기 전까지 해당 컴포넌트의 코드를 로드하지 않으므로 초기 번들 크기를 줄이고 초기 로딩 시간을 단축시킨다.
'[개발] > React' 카테고리의 다른 글
| [React] 리액트 딥다이브 - Hook 정리 (2) | 2023.12.22 |
|---|---|
| [React] Context (0) | 2023.12.15 |
| 비동기 요청 라이브러리 (0) | 2023.06.27 |
| useReducer (0) | 2023.06.27 |
| 최적화 (0) | 2023.06.20 |