๐ Code Splitting in React with Lazy Loading
As React apps grow, so do their bundle sizes. Loading everything at once can slow down performance and hurt user experience. Thatโs where code splitting and lazy loading come in.
In this blog, weโll explore how to split your code and load components only when needed using React.lazy and Suspense.
๐ก What is Code Splitting?
Code splitting means breaking up your JavaScript bundle into smaller chunks that can be loaded on demand.
Benefits:
- ๐ Faster initial page loads
- ๐ฎ Less unused code
- ๐ Better performance for large apps
React supports code splitting out of the box using dynamic import() and React.lazy()
.
๐ Basic Example with React.lazy
import React, { lazy, Suspense } from 'react';
const AboutPage = lazy(() => import('./pages/About'));
function App() {
return (
<div>
<h1>My App</h1>
<Suspense fallback={<div>Loading...</div>}>
<AboutPage />
</Suspense>
</div>
);
}
export default App;
๐ Explanation:
-
lazy()
dynamically loads the component. -
Suspense
shows a fallback UI (like a spinner) until the component is loaded.
๐ Best Practices
- Use lazy loading for non-critical components like modals, settings pages, charts, etc.
- Combine with React Router for route-based code splitting.
- Keep fallbacks lightweight to avoid delays.
๐บ๏ธ Real-World Use with React Router
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Profile = lazy(() => import('./pages/Profile'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading page...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</Suspense>
</Router>
);
}
๐ Bonus: Named Exports with React.lazy
React.lazy only works with default exports. If your component uses named exports, wrap it:
const LazyComponent = lazy(() =>
import('./MyComponent').then(module => ({ default: module.MyComponent }))
);
๐ Final Thoughts
Code splitting and lazy loading are essential for improving performance in large-scale React apps. They help reduce load time, enhance UX, and boost Lighthouse scores!
Start small: lazy load routes, then explore loading components, utilities, or charts on demand.
๐ Useful Links
Thanks for reading! ๐ Feel free to share or comment with questions!
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.