React.lazy cho phép lazy load component, chỉ download JavaScript khi component cần render.
- Suspense hiển thị fallback UI trong khi component đang load.
- Giúp code splitting, giảm initial bundle size.
tsx
import { lazy, Suspense } from 'react'
// Bundle của HeavyChart chỉ download khi cần
const HeavyChart = lazy(() => import('./HeavyChart'))
const Dashboard = () => {
const [showChart, setShowChart] = useState(false)
return (
<div>
<button onClick={() => setShowChart(true)}>Load Chart</button>
{showChart && (
<Suspense fallback={<div>Loading chart...</div>}>
<HeavyChart />
</Suspense>
)}
</div>
)
}React.lazy enables lazy loading of a component — its JavaScript is only downloaded when the component needs to render.
- Suspense shows a fallback UI while the component loads.
- Together they enable code splitting and reduce initial bundle size.
tsx
import { lazy, Suspense } from 'react'
// HeavyChart bundle is only downloaded when needed
const HeavyChart = lazy(() => import('./HeavyChart'))
const Dashboard = () => {
const [showChart, setShowChart] = useState(false)
return (
<div>
<button onClick={() => setShowChart(true)}>Load Chart</button>
{showChart && (
<Suspense fallback={<div>Loading chart...</div>}>
<HeavyChart />
</Suspense>
)}
</div>
)
}