Code splitting is a technique to split your JavaScript bundle into smaller chunks so that the browser loads only what is needed, improving performance and load times.
In React, this is usually done using React.lazy and Suspense, or with dynamic imports.
1️⃣ Why Code Splitting
- Large React apps bundle all code into a single JS file → slow initial load
- Code splitting allows loading parts of the app on demand
- Improves:
- Initial load time
- User experience
- Performance metrics
2️⃣ Using React.lazy and Suspense
import React, { Suspense } from "react";
// Lazy load the component
const Dashboard = React.lazy(() => import("./Dashboard"));
function App() {
return (
<div>
<h1>My App</h1>
<Suspense fallback={<div>Loading...</div>}>
<Dashboard />
</Suspense>
</div>
);
}
export default App;
Explanation:
React.lazy(() => import('./Dashboard'))→ dynamically loads the component<Suspense fallback={...}>→ shows a loading UI while the component is being loaded
3️⃣ Route-based Code Splitting
- Commonly used with React Router for loading pages only when needed
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import React, { Suspense } from "react";
const Home = React.lazy(() => import("./Home"));
const About = React.lazy(() => import("./About"));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading Page...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</Router>
);
}
export default App;
- Only loads the About page when user navigates there → faster initial load
4️⃣ Tips for Code Splitting
- Split by routes or large components
- Keep small shared components outside lazy loading
- Use dynamic imports for libraries or heavy utilities
const Chart = React.lazy(() => import("chart.js"));
⚡ In short:
Code splitting in React loads code on demand, improving performance. Use
React.lazy+Suspensefor component-level splitting, and combine with route-based lazy loading for scalable apps.