Error Handling with Error Boundaries
What you'll learn: How to gracefully handle both loading states and code-split chunk load failures by combining Suspense with Error Boundaries.
The Problem: Code Splits Can Fail
When you use React.lazy() to split your code, you're loading JavaScript chunks over the network. Networks aren't perfect—a user might lose connection mid-load, your CDN might hiccup, or a deployed chunk might be missing. Without error handling, your entire app could crash with a blank screen.
The Solution: Wrap Suspense with an Error Boundary
Since Suspense handles the loading state and Error Boundaries handle errors, combining them creates a complete async boundary:
<ErrorBoundary fallback={<ErrorFallback />}>
<Suspense fallback={<Spinner />}>
<LazyComponent />
</Suspense>
</ErrorBoundary>
How it works:
- While the chunk loads → Suspense shows the spinner
- If loading succeeds → Component renders normally
- If loading fails → Error Boundary catches it and shows the error fallback
Think of It Like a Safety Net
Imagine Suspense as a "please wait" sign while a package is being delivered. The Error Boundary is the backup plan if the delivery truck breaks down—instead of leaving customers confused, you show them a helpful message and maybe a retry button.
Practical Pattern
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div>
<h2>Failed to load component</h2>
<p>{error.message}</p>
<button onClick={resetErrorBoundary}>Try Again</button>
</div>
);
}
The resetErrorBoundary function lets users retry the failed chunk load, which often succeeds after a momentary network issue.
Key Takeaway: Always wrap Suspense boundaries with Error Boundaries when lazy loading components—Suspense handles "not ready yet," Error Boundaries handle "something went wrong."