javascript / intermediate
Snippet
Code Splitting with React.lazy and Suspense
React.lazy allows you to load components dynamically only when they are needed. Combined with Suspense, you can provide a fallback UI while the browser fetches the separate JavaScript chunk, significantly improving initial page load performance.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
import React, { Suspense, lazy } from 'react';const HeavyChart = lazy(() => import('./HeavyChart'));function Dashboard() {return (<Suspense fallback={<div>Loading chart...</div>}><HeavyChart data={stats} /></Suspense>);}
react
Breakdown
1
const HeavyChart = lazy(() => import('./HeavyChart'));
Creates a component that is loaded via a dynamic import expression.
2
<Suspense fallback={...}>
A wrapper that detects when children are waiting for a dynamic resource and shows the fallback instead.