javascript / intermediate
Snippet
Code Splitting with React.lazy and Suspense
React.lazy lets you define a component that is loaded dynamically. This helps reduce the initial bundle size by delaying the loading of code that isn't immediately necessary. Suspense provides a loading state while waiting for the component to load.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
import { lazy, Suspense } from 'react';const HeavyComponent = lazy(() => import('./HeavyComponent'));function App() {return (<Suspense fallback={<div>Loading...</div>}><HeavyComponent /></Suspense>);}
react
Breakdown
1
lazy(() => import('./HeavyComponent'))
Uses dynamic import() to fetch the component file only when it is rendered.
2
<Suspense fallback={...}>
Specifies the UI to show while the lazy-loaded component is being fetched.