Code Splitting Strategies
Route-based, component-based, library splitting, and dynamic imports.
Overview
Code splitting reduces initial bundle size by loading code only when needed.
Key Concepts
- Route Splitting — Separate bundles per route
- Component Splitting — Lazy-load heavy components
- Library Splitting — Load large libraries on demand
- Suspense Boundaries — Show fallbacks while loading
- Prefetching — Load code before user needs it
Code Examples
// Route splitting
const routes = [
{ path: '/', component: () => import('./pages/Home') },
{ path: '/dashboard', component: () => import('./pages/Dashboard') },
{ path: '/settings', component: () => import('./pages/Settings') }
];
// Component splitting with prefetching
function LazyComponent({ importFn, fallback }) {
const Component = lazy(importFn);
return (
<Suspense fallback={fallback || <Spinner />}>
<Component />
</Suspense>
);
}
// Prefetch on hover
function NavLink({ to, children }) {
const prefetch = useCallback(() => {
const link = document.createElement('link');
link.rel = 'prefetch';
link.href = `/static/js/${to.replace('/', '')}.js`;
document.head.appendChild(link);
}, [to]);
return (
<Link to={to} onMouseEnter={prefetch}>
{children}
</Link>
);
}
// Library splitting
function RichTextEditor() {
const [Editor, setEditor] = useState(null);
useEffect(() => {
import('@tiptap/react').then(mod => setEditor(() => mod.Editor));
}, []);
if (!Editor) return <Placeholder />;
return <Editor />;
}
Practice
Implement prefetching for route transitions and measure bundle size reduction.