Course contentsShow
← React
Lesson 1386 of 2,39635. Code SplittingFree lesson

React.lazy() for Component Lazy Loading

Using React.lazy to wrap dynamic imports and create components that load on demand instead of at initial bundle time.

React.lazy() for Component Lazy Loading

What you'll learn: How to use React.lazy() to wrap dynamic imports so components load only when needed, not at startup.

The Core Idea

You've already learned that dynamic import() can fetch JavaScript files on-demand. React.lazy() takes this one step further by converting that dynamic import into a React component you can render just like any other component—except it won't exist in your initial bundle.

Think of it like ordering food: without lazy loading, you prepare every dish at opening time. With React.lazy(), you only cook when a customer orders.

How It Works

React.lazy() wraps a function that returns a dynamic import. It returns a special component that React knows how to handle:

const HeavyChart = React.lazy(() => import('./HeavyChart'));

Now HeavyChart is a component, but its code won't download until you actually render it. React automatically suspends when it encounters this component, triggering the nearest Suspense boundary's fallback.

The Complete Pattern

import { lazy, Suspense } from 'react';

const Dashboard = lazy(() => import('./Dashboard'));

function App() {
  return (
    <Suspense fallback={<div>Loading dashboard...</div>}>
      <Dashboard />
    </Suspense>
  );
}

When <Dashboard /> is rendered, React starts downloading the split bundle. While waiting, the fallback displays. Once loaded, the real component replaces the fallback seamlessly.

Why This Matters

You're reducing your initial bundle size. Users download less JavaScript upfront, so your app starts faster. Heavy features load only when users navigate to them.

Key Takeaway: React.lazy() converts dynamic imports into renderable components that automatically integrate with Suspense, splitting your bundle without changing how you write component hierarchies.