Next.js의 Lazy Loading은 경로 렌더링하는 데 필요한 JavaScript의 양을 줄임으로써 애플리케이션의 초기 로딩 선능을 개선하는 데 도움이 된다.
이를 통해 클라이언트 컴포넌트 및 가져온 라이브러리의 로드를 연기하고 필요할 때만 클라이언트 번들에 포함할 수 있다. 예를 들어 사용자가 모달을 클릭하여 열 때까지 모달 로드를 연기할 수 있다. Next.js에서 Lazy Loading을 구현할 수 있는 방법에는 두 가지가 있다.
- next/dynamic과 함께 동적 Import 사용하기
- Suspense와 함께 React.lazy() 사용하기
기본적으로 서버 컴포넌트는 자동으로 코드 분할되며 스트리밍을 사용하여 서버에서 클라이언트로 UI 조각을 점진적으로 보낼 수 있다. 지연 로딩은 클라이언트 컴포넌트에 적용된다.
- next/dynamic
next/dynamic은 React.lazy()와 Suspense의 합성물이다. 증분 마이그레이션을 허용하기 위해 앱 및 페이지 디렉토리에서 동일한 방식으로 작동한다.
- Examples
Importing Client Components
// app/page.js
'use client'
import { useState } from 'react'
import dynamic from 'next/dynamic'
// Client Components:
const ComponentA = dynamic(() => import('../components/A'))
const ComponentB = dynamic(() => import('../components/B'))
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
export default function ClientComponentExample() {
const [showMore, setShowMore] = useState(false)
return (
<div>
{/* Load immediately, but in a separate client bundle */}
<ComponentA />
{/* Load on demand, only when/if the condition is met */}
{showMore && <ComponentB />}
<button onClick={() => setShowMore(!showMore))>Toggle</button>
{/* Load only on the clinet side */}
<ComponentC />
</div>
)
}
Skipping SSR
React.lazy() 및 Suspense를 사용할 때 클라이언트 컴포넌트는 기본적으로 사전 렌더링(SSR)된다. 클라이언트 컴포넌트에 대한 사전 렌더링을 비활성화하려면 ssr 옵션을 false로 설정하면 된다.
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
Importing Server Components
서버 컴포넌트를 동적으로 import 하면 서버 컴포넌트 자체가 아니라 서버 컴포넌트의 하위인 클라이언트 컴포넌트만 lazy loading 된다.
// app/page.js
import dynamic from 'next/dynamic'
// Server Component:
const ServerComponent = dynamic(() => import('../compoents/ServerComponent')
export default function ServerComponenExample() {
return (
<div>
<serverComponent />
</div>
)
}
Loading External Libraries
import() 함수를 사용하여 필요에 따라 외부 라이브러리를 로드할 수 있다. 이 예제에서는 퍼지 검색을 위해 외부 라이브러리 fuse.js를 사용한다. 모듈은 사용자가 검색 입력을 입력한 후에만 클라이언트에 로드된다.
// app/page.js
'use client'
import { useState } from 'react'
const names = ['Tim', 'Joe', 'Bel', 'Lee']
export default function Page() {
const [results, setResults] = useState()
return (
<div>
<input
type="text"
placeholder="Search"
onChange={async (e) => {
const { value } = e.currentTarget
const Fuse = (await import('fuse.js')).default
setResults(fuse.search(value))
}}
/>
<pre>Results: {JSON.stringify(results, null, 2)}</pre>
</div>
)
}
export default function Page() {
return (
<div>
{/* The loading component will be rendered while <WithCustomLoading /> is loading */}
<WithCustomLoading />
</div>
)
}
Importing Named Exports
명명된 import를 동적으로 가져오려면 import() 함수가 반환한 Promise에서 이를 반환할 수 있다.
// components/hello.js
'use client'
export function Hello() {
return <p>Hello!</p>
}
// app/page.js
import dynamic from 'next/dynamic'
const ClientComponent = dynamic(() =>
import('../components/ClientComponent').then((mod) => mod.Hello)
)
'Next.js' 카테고리의 다른 글
Next.js 12-1 Configuring TypeScript (0) | 2023.06.19 |
---|---|
Next.js 9-8 OpenTelemetry (0) | 2023.06.16 |
Next.js 9-6 Static Assets (0) | 2023.06.14 |
Next.js 9-5 Metadata (1) | 2023.06.13 |
Next.js 9-4 Script Optimization (0) | 2023.06.09 |