Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 132 ยท Performance

Code Splitting with lazy and Suspense

Learn code splitting in React with lazy, Suspense and dynamic import() - route-level splits, preloading on hover, transitions, error handling and what bundlers do - with runnable demos.

When you build a React app for production, a bundler such as Vite or webpack combines your code and its dependencies into JavaScript files. If it produces one giant file, every visitor downloads, parses and runs all of your app before seeing anything, including the admin screens they will never open and the charting library used on a single page. Startup time grows with every feature you add.

Code splitting breaks that single bundle into smaller pieces ("chunks") that the browser loads on demand. React supports it with two tools: lazy, which declares a component whose code is loaded the first time it renders, and Suspense, which shows a fallback while that code is on its way. This lesson explains both, demonstrates them with real runs, and covers the practical questions: where to split, how to preload, how to avoid flicker and how to handle failure. It pairs with use() and Suspense and Transitions.

Dynamic import(): the browser feature underneath

Normal import ... from statements are static: they are resolved before your code runs, and the bundler includes them in the main chunk. The function-like import('path') is different. It is evaluated at run time, returns a promise of the module, and tells the bundler "put this in a separate chunk, and fetch it when this line runs".

JavaScript
const module = await import('./heavy-chart.js');
module.default;      // the default export
module.drawChart;    // a named export

Our editor has no files to import from, so the demos below create tiny modules as data: URLs and import those. The mechanism is the same: a promise that resolves after the module code arrives and runs. In your own project you would write import('./HeavyChart.jsx') and the bundler does the rest.

React.lazy and Suspense

lazy takes a function that returns a promise for a module whose default export is a component:

JSX
import { lazy } from 'react';

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

You then use HeavyChart like any component. The first time React tries to render it, the code has not loaded, so React cannot produce output. It "suspends": it looks upward for the nearest <Suspense> boundary and shows that boundary's fallback instead. When the promise resolves, React renders the real component in place of the fallback.

lazy and Suspense with a fallback

Press "Show chart": for about 150 ms you see Loading chart..., then Chart is ready. The console shows the order: requesting the chart code, then chart module evaluated. Now press "Hide chart" and "Show chart" again. The chart appears at once with no fallback and no new log lines: the module was loaded and evaluated once, and lazy remembers the result. That is the whole contract: the code is requested the first time the component is rendered and cached afterwards.

lazy calls your loader function only once per lazy() declaration, so declare it at module level, never inside a component. A lazy created during render would be a new component type each time, which remounts and reloads on every render (see Reconciliation and Keys).

Where to put the Suspense boundary

A boundary decides how much of the page is replaced by the fallback while something loads. Put it too high and a small widget blanks a whole screen; too low and you get a scatter of tiny spinners.

  • Around the whole app or a route: a safe default, so something always shows.
  • Around a single heavy widget (chart, editor, map): the rest of the page stays visible.
  • Nested boundaries let outer content appear first and inner pieces fill in later; the nearest boundary above the suspended component wins.

Design the fallback to match the final layout (a skeleton with the same height) to avoid layout shift. A fallback is just an element, so it can be anything.

Split by route first

The best place to split is at routes: a user on the home page does not need the settings page code. A route is a natural, large and independent unit, and the user is already expecting navigation to take a moment. Here a two-page app loads each page on first visit.

Route-level splitting

On mount the console prints download Home and run Home. Click Settings: download Settings, run Settings. Click Home and Settings again as often as you like: nothing more is logged. Each page's code is fetched once, and only if the user goes there. (Real routers do the same thing with a lazy option per route; this lesson's state variable stands in for the URL. See Routing.)

Avoiding the flash of fallback with transitions

There is one annoyance in that demo. When you click Settings, the page you were looking at is replaced by the fallback while the new code loads. For a navigation that feels jumpy: the old page disappeared before the new one is ready.

Wrapping the state update in a transition tells React "this update is not urgent, keep showing the current UI until the new one can be displayed". A transition does not hide content that is already visible behind a fallback; isPending lets you show a hint instead.

A transition keeps the old page visible

The very first load still shows Loading first page..., because there is nothing on screen yet to keep. Afterwards, click settings: the Home heading stays, dims to half opacity and a (loading...) label appears next to the buttons; about 150 ms later it swaps to Settings page. Switching back to a page you already loaded is instant. Without startTransition the heading would vanish behind the fallback each time.

Preloading: start before the user clicks

Lazy loading trades startup speed for a delay later. You can hide that delay by starting the download early, for example when the pointer hovers a link or button, or when the browser is idle. The trick is to keep the loader function in a variable so both lazy and your preload code call the same one: the import is only really performed once, and the second call receives the same promise from the module cache.

Preload on hover

Hover the button and the console logs network request started. Wait half a second and click: Editor ready appears at once, with no Loading editor... flash and no second request, because loadEditor returned the promise that the hover had already started. Reload the demo and click without hovering first and you see the fallback for about 150 ms. The loader here caches its promise by hand to imitate what a bundler's module system does for you: a second import('./Editor') for the same file never downloads it twice.

The simplest real-world preload recipe is a plain function:

JSX
// Read-only: requires a bundler (Vite, webpack) that resolves the path
const importEditor = () => import('./Editor');
const Editor = lazy(importEditor);

// Later: hover, focus, idle time, or after the first screen is interactive
function preloadEditor() {
  importEditor();
}

Frameworks and routers add smarter versions: preload the code (and the data) of a link when it enters the viewport or on hover.

Handling failure

Networks fail, and a deploy can remove old chunk files while a user's tab still points at them. If the promise rejects, lazy throws the error during rendering, and with no handler the whole React tree unmounts. You have two defences:

  1. An error boundary around the Suspense boundary, showing a retry button or reloading the page. See Error Boundaries.
  2. A fallback in the loader itself, for the cases where a degraded UI is acceptable:
A loader with a fallback module

The console shows load failed: Failed to fetch dynamically imported module and the page renders the alert paragraph instead of crashing. We simulate the rejection with Promise.reject; in a bundled app the same .catch would be attached to the real import(). Caching the failure is a trap: lazy remembers a rejected promise too, so a "retry" button usually needs a new lazy component or a full page reload.

What the bundler does (read-only)

A typical Vite or webpack project turns each import() into a file in the build output:

TEXT
dist/assets/index-8f3a1c.js        main bundle: React, router, home page   (small)
dist/assets/Settings-2b9d77.js     loaded when /settings is first visited
dist/assets/HeavyChart-91c0aa.js   loaded when the chart first renders

Rules of thumb for your own projects:

  • Default exports only: lazy needs module.default to be the component. For a named export, re-export it: import('./charts').then((m) => ({ default: m.BarChart })).
  • Look at your bundle with a visualizer (for example rollup-plugin-visualizer for Vite, or webpack-bundle-analyzer) before and after splitting; the chunks should shrink the first load noticeably.
  • Split big, rarely used dependencies: markdown editors, charts, maps, PDF viewers, date-picker locales.
  • Do not lazy-load small components or things on the first screen. Every chunk is another network request, and the component above the fold should be in the main bundle.
  • With server rendering frameworks (Next.js, React Router framework mode) the same ideas apply; lazy is replaced or wrapped by the framework's own dynamic import helper, and the server can send fallback HTML first.

Pitfalls professionals know

  • Chunk waterfalls: if a lazy component renders another lazy component, the second download only begins after the first finishes. Preload nested pieces together.
  • Layout shift: a fallback much shorter than the content makes the page jump when it arrives. Reserve space.
  • Stale deployments: after a new release, old chunk file names vanish. Catch the failed import, then reload the page once.
  • Over-splitting: dozens of tiny chunks can be slower than one medium bundle on poor networks. Aim for route-level and heavy-widget-level splits.
  • Suspense is not only for code. The same boundary also shows fallbacks for data read with use(), as described in use() and Suspense.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does React.lazy(() => import('./Chart')) do?

    lazy wraps a loader. React calls it the first time the component is rendered, shows the nearest Suspense fallback until the promise resolves, and then renders the component.
  2. 2. Where should const Chart = lazy(...) be written?

    A lazy component created during render is a new type on every render, so React would remount it and could trigger a fresh load each time.
  3. 3. What happens if a lazy component renders and no Suspense boundary exists above it?

    A suspended component needs the nearest Suspense boundary to decide what to show meanwhile. Without one, React reports an error.
  4. 4. A user switches pages and the old page disappears behind a spinner. Which tool keeps the old page on screen until the new one is ready?

    Transitions mark the update as non-urgent: React keeps the current UI visible, exposes isPending, and swaps when the new UI is ready.
  5. 5. Which of these is the best candidate for code splitting?

    Split large, independent code that many visitors never need. Tiny or above-the-fold components belong in the main bundle.

Summary

  • Code splitting turns one big bundle into chunks that load on demand, so first load is faster.
  • import() returns a promise for a module; lazy wraps it so a component's code loads the first time it renders and is cached afterwards.
  • <Suspense fallback> decides what shows while loading; its position controls how much of the page is replaced.
  • Split by route first, then by heavy widgets; avoid splitting small or above-the-fold components.
  • Use startTransition to keep old UI visible during navigation, and preload on hover or idle to hide the delay.
  • Handle failed loads with an error boundary or a fallback module, and declare lazy components at module level.

Next: The React Compiler