📖 Notes
LESSON 15 OF 18
Code Splitting & Lazy Loading
Loading Only What's Needed
Code splitting means the browser doesn't have to download your entire app upfront — routes the user hasn't visited yet load on demand, keeping the initial page load fast.
lazy + Suspense
Splitting at the Route Level
💤
lazy()
const Player = lazy(() => import("./pages/Player"));
⏳
Suspense
Required wrapper: shows a fallback while the lazy component loads.
🛣️
Route-Level Splitting
The most common pattern — each page loads only when visited.
Lazy-Loaded Routes
JSXimport { lazy, Suspense } from "react";
const Player = lazy(() => import("./pages/Player"));
const Dashboard = lazy(() => import("./pages/Dashboard"));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/player/:id" element={<Player />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
💡
Why this matters at scale
Without code splitting, a user visiting only the homepage still downloads the JS for every other page in the app — lazy loading fixes this by deferring each route's code until it's actually needed.