What is code splitting and how do you use React.lazy and Suspense?
· Category: React
Short answer
Code splitting breaks your bundle into smaller chunks. React.lazy lets you load components dynamically, and Suspense displays a fallback while the chunk is being fetched.
Steps
- Replace static imports with
React.lazy(() => import('./Component')). - Wrap the lazy component in
<Suspense fallback={<Loading />}>. - Handle errors with an Error Boundary because lazy loading can fail.
Example
import { lazy, Suspense } from 'react';
const HeavyChart = lazy(() => import('./HeavyChart'));
function Dashboard() {
return (
<div>
<Suspense fallback={<p>Loading chart...</p>}>
<HeavyChart />
</Suspense>
</div>
);
}
Tips
- Split at route boundaries for the biggest impact.
- Avoid lazy loading components that are needed immediately on first paint.
- Combine with prefetching on hover or scroll to make transitions feel instant.