728x90
next.js 13버전 때 학습내용 정리 문서로 현재와 다름 주의
Lazy Loading
초기 로딩 개선 목적.
필요할때 로딩하게 구현
next/dynamic
클라이언트 컴포넌트 가져오기
'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 client side */}
<ComponentC />
</div>
);
}
SSR 무시
React.lazy() 및 Suspense를 사용할때 클라이언트 컴포넌트는 미리 렌더링(SSR)됨.
끌려면 ssr 옵션을 false로 설정할 것.
const ComponentC = dynamic(() => import('../components/C'), { ssr: false });
서버 컴포넌트 가져오기
서버 컴포넌트를 동적으로 임포트하는 경우 서버 컴포넌트 자체가 아닌 서버 컴포넌트의 자식인 클라이언트 컴포넌트만 지연 로드됨.
import dynamic from 'next/dynamic';
// Server Component:
const ServerComponent = dynamic(() => import('../components/ServerComponent'));
export default function ServerComponentExample() {
return (
<div>
<ServerComponent />
</div>
);
}
외부 라이브러리 가져오기
import() 함수로 필요에 따라 로드할 수 있음.
'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;
// Dynamically load 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>Loading...</p>,
},
);
export default function Page() {
return (
<div>
{/* The loading component will be rendered while <WithCustomLoading/> is loading */}
<WithCustomLoading />
</div>
);
}
명명된 내보내기 가져오기
// hello.js
'use client';
export function Hello() {
return <p>Hello!</p>;
}
// page.js
import dynamic from 'next/dynamic';
const ClientComponent = dynamic(() =>
import('../components/ClientComponent').then((mod) => mod.Hello),
);
'공부공부 > Next.js 공식문서' 카테고리의 다른 글
[next.js 공식문서] 23. OpenTelemetry (0) | 2024.03.05 |
---|---|
[next.js 공식문서] 22. Analytics (0) | 2024.03.05 |
[next.js 공식문서] 20. Static Assets (0) | 2024.03.04 |
[next.js 공식문서] 19. Metadata (0) | 2024.03.03 |
[next.js 공식문서] 18. Script Optimization (0) | 2024.03.03 |