지연 로딩
Next.js의 지연 로딩은 경로를 렌더링하는 데 필요한 JavaScript 양을 줄임으로써 애플리케이션의 초기 로딩 성능을 향상시킵니다.
이를 통해 클라이언트 컴포넌트와 가져온 라이브러리의 로딩을 지연시키고, 필요할 때만 클라이언트 번들에 포함시킬 수 있습니다. 예를 들어, 사용자가 열기 위해 클릭할 때까지 모달의 로딩을 지연시킬 수 있습니다.
Next.js에서 지연 로딩을 구현하는 두 가지 방법이 있습니다:
next/dynamic
을 사용한 동적 가져오기- Suspense와 함께
React.lazy()
사용
기본적으로 서버 컴포넌트는 자동으로 코드 분할되며, 스트리밍을 사용하여 UI 조각을 서버에서 클라이언트로 점진적으로 보낼 수 있습니다. 지연 로딩은 클라이언트 컴포넌트에 적용됩니다.
next/dynamic
next/dynamic
은 React.lazy()
와 Suspense의 조합입니다. 점진적 마이그레이션을 위해 app
과 pages
디렉토리에서 동일하게 동작합니다.
예시
클라이언트 컴포넌트 가져오기
"use client";
import { useState } from "react";
import dynamic from "next/dynamic";
// 클라이언트 컴포넌트:
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>
{/* 즉시 로드하지만 별도의 클라이언트 번들로 */}
<ComponentA />
{/* 조건이 충족될 때만 필요에 따라 로드 */}
{showMore && <ComponentB />}
<button onClick={() => setShowMore(!showMore)}>토글</button>
{/* 클라이언트 사이드에서만 로드 */}
<ComponentC />
</div>
);
}
SSR 건너뛰기
React.lazy()
와 Suspense를 사용할 때, 클라이언트 컴포넌트는 기본적으로 사전 렌더링(SSR)됩니다.
클라이언트 컴포넌트의 사전 렌더링을 비활성화하려면 ssr
옵션을 false
로 설정할 수 있습니다:
const ComponentC = dynamic(() => import("../components/C"), { ssr: false });
서버 컴포넌트 가져오기
서버 컴포넌트를 동적으로 가져오면, 서버 컴포넌트 자체가 아닌 서버 컴포넌트의 자식인 클라이언트 컴포넌트만 지연 로드됩니다.
import dynamic from "next/dynamic";
// 서버 컴포넌트:
const ServerComponent = dynamic(() => import("../components/ServerComponent"));
export default function ServerComponentExample() {
return (
<div>
<ServerComponent />
</div>
);
}
외부 라이브러리 로딩
외부 라이브러리는 import()
함수를 사용하여 필요에 따라 로드할 수 있습니다. 이 예제에서는 퍼지 검색을 위해 외부 라이브러리 fuse.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;
// fuse.js를 동적으로 로드
const Fuse = (await import("fuse.js")).default;
const fuse = new Fuse(names);
setResults(fuse.search(value));
}}
/>
<pre>Results: {JSON.stringify(results, null, 2)}</pre>
</div>
);
}
사용자 정의 로딩 컴포넌트 추가
import dynamic from "next/dynamic";
const WithCustomLoading = dynamic(
() => import("../components/WithCustomLoading"),
{
loading: () => <p>로딩 중...</p>,
}
);
export default function Page() {
return (
<div>
{/* <WithCustomLoading/>가 로딩되는 동안 로딩 컴포넌트가 렌더링됩니다 */}
<WithCustomLoading />
</div>
);
}
명명된 내보내기 가져오기
명명된 내보내기를 동적으로 가져오려면 import()
함수가 반환하는 Promise에서 반환할 수 있습니다:
"use client";
export function Hello() {
return <p>안녕하세요!</p>;
}
import dynamic from "next/dynamic";
const ClientComponent = dynamic(() =>
import("../components/hello").then((mod) => mod.Hello)
);