Lazy Loading Route Components
What You'll Learn
You'll learn how to combine React.lazy() with React Router to load entire page components only when the user navigates to them, drastically reducing your initial bundle size.
The Core Idea
In a typical multi-page React application, every route's component gets bundled together and downloaded on the first load—even pages users might never visit. By applying React.lazy() to route-level components, you split each page into its own JavaScript chunk that only downloads when someone actually navigates there.
Think of it like a restaurant menu: instead of the kitchen preparing every dish at once when you walk in (eager loading), they wait until you order (lazy loading). You get faster service for what you actually want.
How It Works
Instead of importing route components normally:
import Home from './pages/Home';
import About from './pages/About';
Use React.lazy():
const Home = React.lazy(() => import('./pages/Home'));
const About = React.lazy(() => import('./pages/About'));
Then wrap your router with a Suspense boundary:
<Suspense fallback={<div>Loading page...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
Now when users visit /about for the first time, React downloads the About component's code chunk, shows your fallback spinner briefly, then renders the page. The Home component's code never loads unless they visit it.
The Benefits
Route-level code splitting is often the biggest performance win you can achieve with minimal effort. Your initial bundle becomes dramatically smaller, speeding up your app's first load.
Key Takeaway: Apply React.lazy() to route components and wrap your router in a Suspense boundary to load pages on-demand, making your initial app bundle much smaller and faster to download.