Next.jsμμμ Lazy Loading
Lazy Loadingμ μ ν리μΌμ΄μ μμ μꡬλλ 리μμ€λ₯Ό νμν λλ§ λ‘λν΄μ λ‘λ© μλλ₯Ό κ°μ νκ³ μ¬μ©μ κ²½νμ ν₯μμν€λ μ λ΅μ΄λ€.
Next.js μμ Lazy Loading μ μ μ©νλ λ°©λ²μΌλ‘λ λ κ°μ§κ° μλ€.
1. Dynamic Imports
2. React.lazy()μ Suspense
React.lazy()μ Suspense
React.lazy()λ Reactμμ μ 곡νλ λ΄μ₯ κΈ°λ₯μΌλ‘ μ½λλ₯Ό λΆν νμ¬ νμν μμ μ λΉλκΈ°μ μΌλ‘ λ‘λν μ μλλ‘ νλ€.
μ΄μ ν¨κ» Suspenseλ lazy μ»΄ν¬λνΈκ° λ‘λ λλ λμ λ체ν΄μ 보μ¬μ€ μμλ₯Ό μ§μ ν μ μλ€.
React νλ‘μ νΈ μ React Router λΌμ΄λΈλ¬λ¦¬μ ν¨κ» μ¬μ©ν΄μ νμ΄μ§ μ ν λ‘λ© μ€μλ λ€λ₯Έ νμ΄μ§μ μνΈμμ©νμ§ μλλ‘ λ§μ μ μλ€.
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</Router>
);
next/dynamic
next/dynamicμ React.lazy()μ Suspenseμ κΈ°λ₯μ λͺ¨λ ν©μΉ κ²μ΄λ€.
dynamic ν¨μλ λμ μΌλ‘ λ‘λν μ»΄ν¬λνΈμ κ΄λ ¨λ μ€μ κ°μ²΄λ₯Ό μΈμλ‘ λ°λλ€. λ λ²μ§Έ μΈμμ μ΅μ μΌλ‘ loadingμ νμ©νλ©΄ Suspenseμ fallbackμ μ¬μ©ν κ² μ²λΌ ν΄λΉ μ»΄ν¬λνΈκ° λ‘λ© μ€μΈ κ²½μ°μ 보μ¬μ€ μμλ₯Ό μ§μ ν μ μλ€.
import dynamic from 'next/dynamic';
const DynamicHeader = dynamic(() => import('../components/header'), {
loading: () => <p>Loading...</p>,
});
export default function Home() {
return <DynamicHeader />;
}
suspense μ΅μ μ νμ©νλ©΄ reactμ Suspenseμ μ μ¬ν μ»΄ν¬λνΈλ₯Ό μ¬μ©ν μ μλ€.
import dynamic from 'next/dynamic';
const DynamicHeader = dynamic(() => import('../components/header'), {
suspense: true,
});
export default function Home() {
return (<Suspense fallback={<p>Loading...</p>}>
<DynamicHeader />
</Suspense>);
}
μ°Έκ³
https://react.dev/reference/react/lazy
https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading
https://ko.legacy.reactjs.org/docs/code-splitting.html#route-based-code-splitting