24. Optimizing Performance with Code-Splitting and Lazy Loading
Level: AdvancedDuration: 24m
What Is Code-Splitting?
By default, React bundles your entire app into one large JavaScript file. Code-splitting allows you to break your app into smaller chunks so users only load what they need when they need it.
- Improves initial page load time
- Reduces JavaScript bundle size
- Delays loading of rarely used pages
- Boosts performance for slow networks
Lazy Loading with React.lazy
jsx
import React, { Suspense } from 'react'
const About = React.lazy(() => import('./About'))
export default function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<About />
</Suspense>
)
}The About component is loaded only when it is rendered. Until then, React shows a fallback loader.
Route-Based Code Splitting (React Router)
jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom'
const Home = React.lazy(() => import('./Home'))
const Dashboard = React.lazy(() => import('./Dashboard'))
export default function App() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/dashboard' element={<Dashboard />} />
</Routes>
</Suspense>
</BrowserRouter>
)
}Preloading Components
You can preload components before they are needed using dynamic imports.
jsx
const Settings = React.lazy(() => import('./Settings'))
function preloadSettings() {
import('./Settings')
}
<button onMouseEnter={preloadSettings}>Settings</button>When to Use Lazy Loading
| Use Case | Recommended? |
|---|---|
| Large pages or routes | ✅ Yes |
| Admin or dashboard components | ✅ Yes |
| Reusable UI components (buttons/cards) | ❌ No |
| Critical app features | ⚠️ Use carefully |
| Modals and heavy charts | ✅ Yes |
Best Practices
- Always wrap lazy components in Suspense
- Group related components together
- Avoid lazy loading tiny components
- Use preloading for better UX
- Use bundle analyzer to optimize chunk sizes
Mini Project Step
Convert at least 2 routes in your project to lazy-loaded components. Add a friendly loading spinner using Suspense fallback.