javascript / intermediate
Snippet
Code Splitting with React.lazy and Suspense
React.lazy enables you to load components dynamically using the dynamic import() syntax. Combined with Suspense, it allows you to defer loading heavy components until they are actually needed, significantly reducing initial load times.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const AnalyticsChart = React.lazy(() => import('./AnalyticsChart'));function Dashboard() {return (<div><h1>System Status</h1><React.Suspense fallback={<p>Loading chart...</p>}><AnalyticsChart /></React.Suspense></div>);}
react
Breakdown
1
React.lazy(() => import('./AnalyticsChart'))
Defines a component that will be fetched automatically via a separate network request when it first renders.
2
<React.Suspense fallback={...}>
A wrapper that provides a loading UI (fallback) while the lazy-loaded component is being downloaded.