Introduction
As your React application grows, so does your JavaScript bundle size. Large bundles take longer to download, parse, and execute, making your React app feel slow—especially on mobile devices or slow networks. One of the most powerful ways to improve performance is by using code splitting and lazy loading. These techniques allow your app to load only the required code initially and fetch the remaining code when needed. This creates a faster, smoother user experience. In this article, we will explain how code splitting and lazy loading work, why they matter, and how to use them effectively with React.
What Is Code Splitting?
Code splitting means breaking your JavaScript bundle into smaller chunks instead of loading one large file.
Why Code Splitting Improves Performance
Reduces initial load time
Sends only the required code to the browser
Improves Time to Interactive (TTI)
Enhances SEO and Core Web Vitals
Without Code Splitting
Your entire React app loads at once—even if the user needs only one page.
With Code Splitting
React loads only the code for the current page and fetches the rest when needed.
Using React.lazy for Component-Level Code Splitting
React.lazy() allows you to load components only when they are needed.
Basic Example
import React, { Suspense } from "react";
const About = React.lazy(() => import("./About"));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<About />
</Suspense>
);
}How It Works
React.lazy()dynamically imports the componentSuspenseshows a loading indicator while the component loads
When to Use
Large components
Pages in routing
Dashboard widgets
Modals, charts, maps
Code Splitting with React Router
You can lazy load entire pages using React Router.
Example
import { BrowserRouter, Routes, Route } from "react-router-dom";
import React, { Suspense } from "react";
const Home = React.lazy(() => import("./pages/Home"));
const Profile = React.lazy(() => import("./pages/Profile"));
const Settings = React.lazy(() => import("./pages/Settings"));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
Join the conversation! Your thoughts help the community grow.