Trung BìnhReact iconReact

React.lazy và Suspense dùng để làm gì?

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>
  )
}

Xem toàn bộ React cùng filter theo level & chủ đề con.

Mở danh sách React