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

Error Boundaries for Route Chunks

Wrapping lazy routes in error boundaries to gracefully handle chunk load failures and network errors during navigation.

Error Boundaries for Route Chunks

What you'll learn: How to catch and recover from errors when lazy-loaded route components fail to download or execute.

When you split routes into separate chunks using React.lazy(), those chunks can fail to load—users might lose their network connection mid-navigation, your CDN might hiccup, or a deployment might invalidate old chunk URLs. Without protection, these failures crash your entire app with a blank screen.

The Problem

Route chunks are network requests. They can fail. A lazy route component that throws during loading (or fails to fetch) will bubble up as an error, just like any other React error.

The Solution: Wrap Routes in Error Boundaries

Place an Error Boundary around your lazy route components (or the <Suspense> boundary wrapping them). When a chunk fails to load, the Error Boundary catches it and displays a fallback UI instead of crashing.

<ErrorBoundary 
  fallback={<RouteError />}
  onReset={() => window.location.reload()}
>
  <Suspense fallback={<Spinner />}>
    <LazyRoute />
  </Suspense>
</ErrorBoundary>

The fallback shows users a friendly message like "This page failed to load" with a retry button. The onReset handler can refresh the page to re-fetch the chunk.

Why This Matters

Network failures during navigation are expected in production apps with code splitting. Without Error Boundaries, your users see a white screen with cryptic console errors. With them, you provide graceful degradation and recovery options.

Key Takeaway: Always wrap lazy-loaded routes in Error Boundaries to catch chunk loading failures and provide users with retry mechanisms instead of complete app crashes.