# Code Splitting & <Suspense>

> How to dramatically improve your app's load time by splitting your JavaScript bundle and loading components only when needed.

Subject: React | Lesson 33 of 48 | 5 min read
Interactive lesson: https://codewithanimation.in/react/code-splitting-suspense
Previous: [The Over-Optimization Trap](https://codewithanimation.in/react/over-optimization-trap.md) | Next: [List Virtualization](https://codewithanimation.in/react/list-virtualization.md)

## The Monolith Problem

By default, tools like Webpack or Vite bundle your entire React application—every page, every modal, every heavy chart library—into a single massive `bundle.js` file.

When a user visits your homepage, their browser has to download, parse, and execute that entire 5MB file before they can click a single button. This results in terrible Time to Interactive (TTI) scores.

Code Splitting is the process of breaking that monolith into smaller, on-demand chunks.

## React.lazy() and <Suspense>

React provides a built-in way to dynamically import components using `React.lazy()`. Instead of importing a heavy component at the top of the file, you tell React to only fetch its JavaScript code when it's actually rendered on the screen.

While the browser is fetching that new JavaScript chunk over the network, React needs something to show the user. This is what `<Suspense>` does: it displays a fallback UI (like a skeleton loader or spinner) while the inner component's code is downloading.

## Dynamic Imports in Action

First, dynamically import the component:

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

Then, wrap it in a Suspense boundary when you render it:

`<Suspense fallback={<Spinner />}>`
  `<HeavyChart data={data} />`
`</Suspense>`

If the user never navigates to the page with the chart, they never pay the performance penalty of downloading the chart library's JavaScript!

## Common mistake: The Waterfall Trap

A common mistake is deeply nesting `React.lazy()` components. If Component A dynamically loads Component B, which dynamically loads Component C, the browser has to wait for A to download before it even *knows* it needs to download B.

This creates a network waterfall. To avoid this, it is best practice to code-split at the Route level (e.g., splitting `/dashboard` from `/settings`), so the chunk boundaries are flat and predictable.

## Tip: Suspense is for Data, Too

Originally, `<Suspense>` was only used for code-splitting (waiting for JavaScript files). Today, in modern React (and frameworks like Next.js), `<Suspense>` is also used to wait for Data fetching! It acts as a universal 'waiting room' for both code and data.

## Try it: The Network Pipe

Interact with the diagram below to simulate a user loading an application over a 3G connection. Compare downloading the monolithic 5MB bundle vs loading just the 500KB shell instantly, and deferring the rest.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/code-splitting-suspense

## Check yourself

### Question 1

What does `React.lazy()` actually do under the hood?

- A. It prevents a component from re-rendering until its props change.
- B. It tells the bundler to put the component in a separate file, and tells the browser to download it only when the component is rendered.
- C. It delays the rendering of a component to 60 frames per second.

Correct answer: B

`React.lazy()` utilizes dynamic `import()` syntax, which modern bundlers (Webpack, Vite) recognize as a signal to split the bundle. It then handles the asynchronous loading state for React.

- Why not A: That is React.memo.

### Question 2

What happens if a `React.lazy()` component is rendered, but it is NOT wrapped in a `<Suspense>` boundary anywhere in the tree?

- A. The app will crash with an error.
- B. React will automatically show a blank white screen.
- C. React will synchronously block the main thread until the code downloads.

Correct answer: A

A suspended component MUST have a parent `<Suspense>` boundary to catch it and display a fallback. If it reaches the root without finding one, React throws an error.

### Question 3

Where is generally the best place to introduce Code Splitting in a standard React Single Page Application?

- A. At the route level (e.g., each page is lazy-loaded).
- B. On every single component in the application.
- C. Only on HTML form inputs.

Correct answer: A

Route-level code splitting is the most effective strategy. Users downloading the 'Login' page don't need the Javascript for the 'Admin Dashboard' until they actually log in and navigate there.

- Why not B: This creates massive overhead and network waterfalls.

## Remember this

- Code splitting breaks your large `bundle.js` into smaller, on-demand files.
- `React.lazy()` allows you to dynamically import a component.
- `<Suspense>` provides the fallback UI (loading state) while the code downloads.
- Code-split at the Route level first, then on massive isolated components (like complex charts or rich text editors).
- Modern React also uses Suspense for data fetching, not just code fetching.
