Lazy Loading Routes with React.lazy
You'll learn how to apply React.lazy to route components so each page loads only when navigated to, automatically showing loading states.
The Core Idea
Route-level code splitting is the most impactful place to apply lazy loading. Instead of bundling all your pages together, you load each route's component on-demand when the user navigates to it. This means your initial bundle only contains the homepage code, not your dashboard, settings, profile, and every other page.
You've already learned React.lazy() for components. Routes are just components triggered by your router, so the pattern is identical: wrap your lazy route components in a Suspense boundary, typically at the route configuration level.
How It Works
Think of your app like a library where each room (route) has its own door. Without lazy loading, you carry books from every room with you. With lazy routes, you only grab the books you need when you enter each room.
Your router (React Router, for example) doesn't care whether components are lazy or eager—it just renders them. So you replace:
import Dashboard from './Dashboard';
with:
const Dashboard = React.lazy(() => import('./Dashboard'));
Then wrap your route rendering in Suspense:
<Suspense fallback={<PageSpinner />}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
Now when users navigate to /dashboard, they see your PageSpinner briefly while that route's code downloads, then the dashboard appears.
Why This Matters
Route-level splitting gives you the biggest bundle size wins with the least effort. Users only pay for what they use. Someone who never visits your admin panel never downloads that code.
Key Takeaway: Lazy loading routes with React.lazy means each page becomes a separate code chunk that loads on navigation, automatically showing your Suspense fallback during the download.