React ยท Chapter 34 of 42

Code Splitting & Lazy Loading

Code splitting breaks your app's JavaScript bundle into smaller chunks that load on demand, reducing the initial load time. React supports this natively with `React.lazy` and `Suspense`.

This is especially valuable for routes or heavy components that aren't needed immediately on page load.

React.lazy

`const About = React.lazy(() => import('./About'));` loads the component's code only when it's actually rendered.

Suspense fallback

Wrap lazy components in `<Suspense fallback={<Spinner />}>` to show a fallback UI while the chunk loads.

Example 1 (jsx)
import { lazy, Suspense } from "react";

const About = lazy(() => import("./About"));

function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <About />
    </Suspense>
  );
}
Output
Loading... then the About component's content

About's code loads on demand, showing a fallback until it's ready.

Key points

  • Code splitting reduces the size of the initial JS bundle.
  • React.lazy() dynamically imports a component's code.
  • Suspense shows a fallback UI while the lazy chunk loads.
  • Commonly applied at the route level for the biggest wins.
๐Ÿ’ก Note: React.lazy currently supports default exports only for the lazily-loaded module.

๐Ÿ“ Quick Quiz

1. What does React.lazy do?

2. What must wrap a lazy-loaded component?

3. Why use code splitting?