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

Error Boundaries with Lazy Components

Catching network failures or loading errors for lazy components using Error Boundaries alongside Suspense.

Error Boundaries with Lazy Components

What you'll learn: How to gracefully handle loading failures when lazy-loaded components fail to download or execute.

The Problem: Networks Can Fail

When you use React.lazy() to split code, you're loading JavaScript over the network. Networks fail. Users lose connections. CDNs have outages. If a lazy component fails to load, React needs somewhere to catch that error—otherwise your entire app crashes.

The Solution: Combine Error Boundaries with Suspense

You've already learned that Suspense handles the loading state and Error Boundaries catch render errors. When lazy loading fails, it becomes a render error that Error Boundaries can catch.

import { lazy, Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';

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

function Dashboard() {
  return (
    <ErrorBoundary fallback={<div>Failed to load chart. Refresh?</div>}>
      <Suspense fallback={<div>Loading chart...</div>}>
        <HeavyChart />
      </Suspense>
    </ErrorBoundary>
  );
}

How It Works

  1. Suspense catches the "loading" state (the thrown promise)
  2. If the network request succeeds, the component renders normally
  3. If the network request fails (404, timeout, parse error), an error is thrown
  4. The Error Boundary catches that error and shows your fallback UI

Think of it like a safety net beneath a trapeze: Suspense is the trapeze platform (waiting area), but if something goes wrong mid-flight, the Error Boundary catches the fall.

Typical Pattern

Wrap lazy components in both boundaries—Error Boundary on the outside, Suspense on the inside. This gives users feedback for both loading and failure states.

Key Takeaway: Always wrap React.lazy() components with both a Suspense boundary (for loading) and an Error Boundary (for network/loading failures) to handle all possible states gracefully.