Skip to the content

Lesson 173 of 296

Error boundaries and Suspense

What you will learn

  • What happens when a component throws
  • Error boundaries and what they catch
  • Writing one, and the react-error-boundary library
  • Suspense for loading states
  • Suspense with lazy components, data and the use() hook
On this page

When a component throws

If a component throws an error while rendering and nothing catches it, React removes the whole app from the screen (a blank page), because showing broken UI could be worse. Error boundaries prevent this.

Error boundaries

An error boundary is a component that catches errors thrown while rendering its children, logs them, and shows a fallback UI instead of crashing everything.

Error boundaries must still be written as class components (there is no hook for this yet):

TSX
import { Component, type ErrorInfo } from "react";

type BoundaryProps = { fallback: ReactNode; children: ReactNode };
type BoundaryState = { hasError: boolean };

class ErrorBoundary extends Component<BoundaryProps, BoundaryState> {
  state: BoundaryState = { hasError: false };

  static getDerivedStateFromError(): BoundaryState {
    return { hasError: true };
  }

  componentDidCatch(error: Error, info: ErrorInfo): void {
    console.error("UI error", error, info.componentStack);
  }

  render() {
    return this.state.hasError ? this.props.fallback : this.props.children;
  }
}
  • getDerivedStateFromError switches to the fallback.
  • componentDidCatch is where you report the error (for example to Sentry).

Usage: wrap parts of the page, so one broken widget does not take down the rest:

TSX
function Dashboard() {
  return (
    <>
      <ErrorBoundary fallback={<p>Sales chart unavailable.</p>}>
        <SalesChart />
      </ErrorBoundary>
      <ErrorBoundary fallback={<p>Orders unavailable.</p>}>
        <RecentOrders />
      </ErrorBoundary>
    </>
  );
}

function SalesChart() {
  return <div>chart</div>;
}

function RecentOrders() {
  return <div>orders</div>;
}

In practice most teams use the react-error-boundary library, which adds a "try again" reset button and hooks such as useErrorBoundary to show async errors in the boundary.

What error boundaries do NOT catch

Not caughtHandle with
Errors in event handlerstry...catch in the handler, then set error state
Errors in async code (promises, timeouts)catch, then set error state (or showBoundary from react-error-boundary)
Errors in the boundary itselfA boundary higher up
Errors during server renderingThe framework's error handling (Next.js has error.tsx, Part 13)

A common interview question.

Suspense

Suspense shows a fallback (such as a spinner or skeleton) while something inside it is not ready yet:

TSX
function ReportsArea() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <AdminArea showReports />
    </Suspense>
  );
}

What can "suspend":

  • Lazy-loaded components (Lesson 172).
  • Data, when using a Suspense-enabled data source: Next.js server components (Part 13), TanStack Query's suspense mode, or React 19's use() hook with a promise.

You do not fetch in an effect to use Suspense; the data source must support it.

The use() hook (React 19)

use(promise) reads the result of a promise. While it is pending, the nearest Suspense shows its fallback; if it rejects, the nearest error boundary catches it. The promise must be created outside the component (for example passed in as a prop from a server component, or cached), not created fresh in every render.

function Comments({ commentsPromise }: { commentsPromise: Promise<string[]> }) {
  const comments = use(commentsPromise);
  return <ul>{comments.map((c) => <li key={c}>{c}</li>)}</ul>;
}

Designing loading and error states together

<ErrorBoundary fallback={<OrdersError />}>
  <Suspense fallback={<OrdersSkeleton />}>
    <Orders />
  </Suspense>
</ErrorBoundary>

The boundary catches failures; Suspense handles waiting. Place them around meaningful sections, so the rest of the page stays usable. Next.js does this per route with loading.tsx and error.tsx files (Part 13).

How to say it in an interview

"An error boundary catches errors thrown while rendering its subtree and shows a fallback instead of unmounting the whole app; it is still a class component with getDerivedStateFromError and componentDidCatch, or I use react-error-boundary for resets. Boundaries do not catch errors in event handlers or async code, so I handle those with try-catch and state. Suspense shows a fallback while children are not ready, for lazy components or Suspense-enabled data like server components or the use hook. I wrap meaningful sections in both so one failure or slow section does not block the page."

Key words

WordMeaning
Error boundaryA component that catches render errors in its children
FallbackThe UI shown instead of the failed or loading content
SuspenseShows a fallback while children are loading
use()A React 19 hook that reads a promise or context
SkeletonA grey placeholder shaped like the content that is loading

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.