Error Boundaries and Fallback UI in React Apps

Shaz3e blog cover for a react error boundary guide titled Error Boundaries and Fallback UI in React Apps.

A single child that throws during render is still enough for React to take down the tree and leave a blank screen. A react error boundary stops that. It catches the failure in a subtree, swaps in a fallback UI, and gives you a place to report the error to a tracker. The rest of the page can keep working.

That matches the front-end layering in my guide to structuring large React applications: isolate features so a crash in the invoice panel does not also kill the sidebar and the nav. Below is a small, tested boundary, a fallback that does not leak stack traces, and a reporter you can point at your own endpoint. I will also cover Next.js error.js, because the App Router already wraps a route segment in an error boundary once you add that file.

What this post covers

Tested versions

ToolVersion
React19.3.1
react-dom19.3.1 (createRoot)
Node.jsv24.22.1
jsdom27.0.1, used only in the tests
Teststest-error-boundary.mjs: 11 checks, all passing

The sample UI is a deals page with a sidebar and an invoice panel. The copy is invented for the tests, not client or product text. The Next.js section follows the current error.js docs (retry became stable in Next.js 16.3). I did not boot a full Next.js app in this run; the route-level fallback was tested as a Client Component with the same props the docs describe.

What a react error boundary actually catches

React’s own docs on catching rendering errors with an error boundary are the source of truth. A boundary catches errors thrown while rendering a child, in a child’s lifecycle, or in a constructor of a child. It does not catch errors in event handlers, in setTimeout or promise callbacks, in the boundary component itself, or in server code that never reaches the tree.

That last point is the one that surprises people. Wrapping <Child /> in try/catch does nothing, because the throw happens later, inside React’s render, not in your function body. Validation mistakes in a form are also the wrong target: those are expected input problems and belong in the form layer, which I walked through in React Hook Form with Zod. Use a boundary for unexpected render failures, not for a missing email address.

React 19 also added onCaughtError and onUncaughtError on createRoot. Those are reporting hooks at the root. They do not replace a boundary, because they do not render a fallback. I still want the UI to recover in place; the root callbacks are a complement, not a substitute.

A small ErrorBoundary you can drop in

There is still no hook for this. You write one class, reuse it, and keep the fallback and the reporter as function components. The official docs mention the react-error-boundary package as an alternative. I rolled a small one so the tests can pin down reset behavior and reporter failures.

import { Component } from "react";

export class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
    this.reset = this.reset.bind(this);
  }

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    const { onError } = this.props;
    if (typeof onError !== "function") return;
    try {
      onError(error, info);
    } catch {
      // A failing reporter must not take down the fallback UI.
    }
  }

  reset() {
    this.setState({ error: null });
  }

  render() {
    const { error } = this.state;
    if (error) {
      const { fallback: Fallback } = this.props;
      if (typeof Fallback === "function") {
        return Fallback({ error, reset: this.reset });
      }
      return Fallback ?? null;
    }
    return this.props.children;
  }
}

getDerivedStateFromError is a pure state update. It is what actually switches the UI to the fallback. componentDidCatch is for side effects: send the error to a tracker, attach the component stack, and stop there. I wrap onError in its own try/catch because a broken reporter should not take the fallback down with it. The tests cover that case.

Fallback UI that is useful, not a blank screen

A fallback that says “Something went wrong” and nothing else is only slightly better than a white screen. I want three things: a short explanation, a way to retry, and no stack traces in the DOM. In production I also hide the raw exception message, because I have seen tokens and payload fragments end up in error.message.

export function FallbackUI({
  error,
  reset,
  title = "This section could not be loaded",
  showDetails = false,
}) {
  const message = showDetails && error instanceof Error && error.message
    ? error.message
    : "This section hit a problem. The rest of the page should still work.";

  return (
    <div role="alert" className="error-fallback">
      <h2>{title}</h2>
      <p>{message}</p>
      {typeof reset === "function" && (
        <button type="button" onClick={reset}>Try again</button>
      )}
    </div>
  );
}

role="alert" is there so a screen reader hears the change. The retry button calls reset, which clears the boundary state and renders the children again. One test I care about: updating the parent so the child would now succeed does not clear the fallback on its own. The user has to click Try again. That is easy to get wrong if you assume a prop change will unstick the boundary.

If the app is translated, this copy belongs in a catalog with the rest of the UI, the same way I treat strings in the React internationalization post. Hardcoded English is fine for the sample; it is not fine once Arabic or Urdu is a real locale.

Reporting errors to a tracker

A fallback without a report is a dead end. You will hear “the invoices tab is broken” and have no component stack and no timing. componentDidCatch receives the thrown value and an info object with componentStack. I serialize a small payload and POST it. The fetch implementation is injectable so the tests can assert on the body without a network.

export function createErrorReporter({ endpoint, fetchImpl } = {}) {
  if (!endpoint) throw new Error("createErrorReporter requires an endpoint");
  const doFetch = fetchImpl ?? globalThis.fetch;

  return async function reportError(error, info) {
    const payload = {
      name: error instanceof Error ? error.name : "Error",
      message: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined,
      componentStack: info?.componentStack,
    };
    try {
      await doFetch(endpoint, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(payload),
      });
    } catch {
      // ignore transport errors
    }
  };
}

Keep the payload tight: name, message, stack, component stack. Do not spread the whole error object or the current user record into the request. If the tracker is down, swallow the failure. The tests confirm a rejected fetch does not throw out of the reporter, and a throwing onError still leaves the fallback on screen.

Wire it at the boundary, not only in window.onerror. In development, errors that a boundary already caught can still surface on window; in production they often do not. If you only listen at the window, you will under-report the failures you already handled in the UI. Root-level onCaughtError is a good second line, as long as it does not double-count the same event you already sent from componentDidCatch.

Where to place the boundary

One boundary around the entire app is better than a white screen, but it is a blunt tool. If the invoice panel throws, I still want the deals list and the nav. The placement I use looks like this:

function BillingPage() {
  return (
    <div>
      <Sidebar />
      <ErrorBoundary
        onError={reportError}
        fallback={(props) => <FallbackUI {...props} />}
      >
        <InvoicePanel />
      </ErrorBoundary>
    </div>
  );
}

The tests render that shell. When the invoice panel throws, the sidebar text is still in the document and the fallback replaces only the panel. That is the whole point of feature-level placement. I would do the same around a widget, a preview, or a third-party chart that I do not fully trust.

Do not wrap every tiny component. You will hide real integration bugs and fill the page with retry buttons. Route or feature boundaries are enough. And do not use a boundary to paper over a backend that is actually down. If a Laravel deploy is returning 500s, the fix is on the server; I wrote about that failure mode in Laravel 500 errors after a deploy on the ResellerBytes blog. The UI should say the request failed and report it, not pretend the panel is fine.

Next.js error.js and global-error.js

In the App Router you do not have to mount the class yourself at the route level. Add an error.js (or error.tsx) file to a segment and Next.js wraps that segment and its nested children in a React error boundary. The file must be a Client Component. The official reference is the error.js file convention linked above.

The component receives the thrown value as error and a retry function. retry became stable in Next.js 16.3; it re-fetches and re-renders the segment. Older examples used reset only. reset is still there if you specifically want to clear the error and re-render without a re-fetch. For a route file, I use retry.

'use client' // error.js must be a Client Component

import { useEffect } from 'react'

export default function Error({ error, retry }) {
  useEffect(() => {
    reportError(error)
  }, [error])

  const digest = error && typeof error === 'object' ? error.digest : null

  return (
    <div role="alert">
      <h2>This page could not be loaded</h2>
      <p>You can try again. If it keeps failing, the error has been reported.</p>
      {digest ? <p>Reference: {digest}</p> : null}
      <button type="button" onClick={() => retry()}>Try again</button>
    </div>
  )
}

Two details from the docs are easy to miss. First, error.js does not wrap the layout.js or template.js in the same segment. A throw in that layout bubbles to the parent segment’s boundary. Errors in the root layout need app/global-error.js, and that file has to render its own <html> and <body> because it replaces the root layout. Second, Server Component errors arrive on the client as a generic message plus a digest you can match to server logs. I show the digest as a reference and keep the raw server message off the page. The tests assert that.

Use error.js for route segments. Keep the class boundary for a widget inside a page that should fail on its own. They solve the same problem at different granularities.

FAQ

Can I write the boundary as a function component?

Not today. getDerivedStateFromError and componentDidCatch exist only on class components. Write one class, reuse it, and keep the fallback as a function component.

Will this catch a throw inside an onClick handler?

No. Event handlers, setTimeout, and promise callbacks are outside render. Catch those at the source, set local error state, or report them yourself. The boundary is for render-time failures.

Should every component have its own boundary?

No. Put them at feature or route edges. A boundary on every leaf hides integration bugs and turns a real failure into a scatter of retry buttons.

Does error.js replace a custom ErrorBoundary?

For a route segment, yes: add error.js and let Next.js wrap it. For a panel inside an otherwise healthy page, keep a component-level boundary so the rest of the page stays up.

I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *