0 day streak
javascript / beginner
Snippet

Code Splitting Components with React.lazy and Suspense

React.lazy enables dynamic, asynchronous loading of component bundles on demand. Wrapping lazy components with Suspense lets you define a fallback placeholder, reducing initial bundle size and improving web page loading performance.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React, { Suspense, lazy } from 'react';
const AnalyticsDashboard = lazy(() => import('./AnalyticsDashboard'));
function App() {
return (
<div>
<h1>Admin Area</h1>
<Suspense fallback={<p>Loading dashboard bundle...</p>}>
<AnalyticsDashboard />
</Suspense>
</div>
);
}
react
Breakdown
1
const AnalyticsDashboard = lazy(() => import('./AnalyticsDashboard'));
Dynamically imports the component chunk asynchronously when it is first needed.
2
<Suspense fallback={<p>Loading dashboard bundle...</p>}>
Specifies a temporary fallback JSX element to display while the dynamic bundle is downloading.
3
<AnalyticsDashboard />
Renders the deferred component once the module has finished loading.