Code Splitting
Learn code splitting techniques to reduce bundle size and improve loading performance. This is a foundational concept in component-based UI development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React experience. Take your time with each section and practice the examples
65 min•By Priygop Team•Last updated: Feb 2026
What is Code Splitting?
Code splitting is a technique that allows you to split your code into various bundles which can be loaded on demand or in parallel. It helps reduce the initial bundle size and improve loading performance.
React.lazy and Suspense
Example
import React, { Suspense, lazy } from 'react';
import { Routes, Route } from 'react-router-dom';
// Lazy load components
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
const Contact = lazy(() => import('./pages/Contact'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
// Loading component
function LoadingSpinner() {
return (
<div className="loading">
<div className="spinner"></div>
<p>Loading...</p>
</div>
);
}
// App with code splitting
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Suspense>
);
}
// Conditional lazy loading
function ConditionalComponent({ shouldLoad }) {
const [Component, setComponent] = useState(null);
useEffect(() => {
if (shouldLoad) {
const LazyComponent = lazy(() => import('./HeavyComponent'));
setComponent(() => LazyComponent);
}
}, [shouldLoad]);
if (!Component) return null;
return (
<Suspense fallback={<div>Loading component...</div>}>
<Component />
</Suspense>
);
}Dynamic Imports
Example
// Dynamic imports with error handling
function DynamicComponent({ componentName }) {
const [Component, setComponent] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const loadComponent = async () => {
try {
const module = await import(`./components/${componentName}`);
setComponent(() => module.default);
} catch (err) {
setError(err.message);
}
};
loadComponent();
}, [componentName]);
if (error) return <div>Error loading component: {error}</div>;
if (!Component) return <div>Loading...</div>;
return <Component />;
}
// Preloading components
function PreloadButton({ componentName, onLoad }) {
const preloadComponent = async () => {
try {
await import(`./components/${componentName}`);
onLoad();
} catch (error) {
}
};
return (
<button onClick={preloadComponent}>
Preload {componentName}
</button>
);
}