How to Manage State Across Multiple Pages :👈 👉:How to Organize a Large React Codebase

How to Design Error Boundaries in React

How to Design Error Boundaries in React

1. What Are Error Boundaries in React?

An Error Boundary is a React component that catches JavaScript errors in its child component tree during rendering and displays a fallback UI instead of allowing the entire application section to fail.

For example, consider an e-commerce application with these sections:

  • Header
  • Product List
  • Shopping Cart
  • User Profile

Suppose the Product List component throws an error while rendering. Without an Error Boundary, the affected part of the application may fail.

With an Error Boundary, we can display a fallback message such as:

Something went wrong while loading products.
Please try again.

Other sections of the application can continue working if they are outside the failed boundary.

2. Why Do We Need Error Boundaries?

React applications can encounter errors because of:

  • Unexpected data returned by components.
  • Incorrect property access.
  • Rendering errors.
  • Third-party component failures.
  • Unexpected errors in child components.

Error Boundaries help to:

  • Prevent a component rendering failure from affecting unrelated application sections.
  • Display a user-friendly fallback interface.
  • Provide a recovery option.
  • Capture error information for debugging.
  • Improve application reliability.

3. How Does an Error Boundary Work?

An Error Boundary works by wrapping other components.

When a descendant component throws an error during rendering, React activates the nearest Error Boundary and displays its fallback UI.

Layer 1 Application Header Remains Visible Footer Remains Visible Error Boundary Protected Components Product List Product Card Product Details Pagination Error thrown Fallback UI Something went wrong Try Again Only boundary contents are replaced

The nearest Error Boundary handles the rendering error. A boundary cannot catch errors thrown by its own fallback UI; an outer boundary may handle those errors.

4. How to Create an Error Boundary

React provides two lifecycle methods used to implement Error Boundaries in class components:

  • getDerivedStateFromError(): Updates state so the component can render a fallback UI.
  • componentDidCatch(): Receives error information and can be used for logging.

Example:

import React from "react";
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false
    };
  }
  static getDerivedStateFromError(error) {
    return {
      hasError: true
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error("Error caught:", error);
    console.error("Component stack:", errorInfo.componentStack);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h2>Something went wrong.</h2>
          <p>Please try again later.</p>
        </div>
      );
    }
    return this.props.children;
  }
}
export default ErrorBoundary;

How this works:

  1. The Error Boundary starts with hasError: false.
  2. React renders its child components normally.
  3. If a descendant throws a rendering error, React calls getDerivedStateFromError().
  4. The state changes to hasError: true.
  5. The fallback UI is displayed.
  6. componentDidCatch() can log the error for debugging.

Important: Error Boundaries are still implemented using class components in React's built-in API. There is no built-in function component equivalent that uses a Hook to catch rendering errors.

5. How to Use an Error Boundary

After creating the Error Boundary, wrap the components that need protection.

Example:

import ErrorBoundary from "./ErrorBoundary";
import ProductList from "./ProductList";
function App() {
  return (
    <div>
      <h1>My Shopping Application</h1>
      <ErrorBoundary>
        <ProductList />
      </ErrorBoundary>
    </div>
  );
}
export default App;

If ProductList or one of its descendant components throws a rendering error, the Error Boundary displays its fallback UI.

6. Where Should We Place Error Boundaries?

One of the most important design decisions is deciding where to place Error Boundaries.

Avoid placing only one boundary around the entire application if independent sections should be able to recover separately.

For example, consider an e-commerce application:

Layer 1 App Header ErrorBoundary ProductList ErrorBoundary ShoppingCart ErrorBoundary UserProfile Footer Isolated Failure Isolated Failure Isolated Failure

With this design:

  • If ProductList fails, its fallback UI is displayed.
  • ShoppingCart can continue working.
  • UserProfile can continue working.
  • Header and Footer remain outside those boundaries.

Recommended placement:

Application AreaRecommended Boundary
Entire applicationRoot Error Boundary
Dashboard widgetsIndividual widget boundaries
Product listingProduct section boundary
Third-party componentsDedicated boundary
Independent page sectionsSeparate boundaries

7. Designing a Reusable Error Boundary

Instead of repeating fallback UI in multiple places, create a reusable Error Boundary that accepts a fallback component.

Example:

import React from "react";
class ErrorBoundary extends React.Component {
  state = {
    hasError: false
  };
  static getDerivedStateFromError() {
    return {
      hasError: true
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error(error, errorInfo);
  }
  render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        <h2>Something went wrong.</h2>
      );
    }
    return this.props.children;
  }
}
export default ErrorBoundary;

Usage:

function ProductError() {
  return (
    <div>
      <h3>Unable to display products</h3>
      <p>Please try again later.</p>
    </div>
  );
}
function App() {
  return (
    <ErrorBoundary fallback={<ProductError />}>
      <ProductList />
    </ErrorBoundary>
  );
}

Now the same Error Boundary can be reused for different application sections with different fallback interfaces.

8. Adding a Retry Mechanism

Displaying an error message is useful, but providing a retry option can improve the user experience.

For example, if a component fails because of temporary data or application conditions, the user may want to try rendering it again.

Example:

import React from "react";
class ErrorBoundary extends React.Component {
  state = {
    hasError: false
  };
  static getDerivedStateFromError() {
    return {
      hasError: true
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error(error, errorInfo);
  }
  resetError = () => {
    this.setState({
      hasError: false
    });
  };
  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h2>Something went wrong.</h2>
          <button onClick={this.resetError}>
            Try Again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

Important: Resetting the Error Boundary only allows the child tree to render again. It does not automatically fix the underlying error. If the same problem still exists, the boundary may catch it again.

For more reliable recovery, reset the boundary when the relevant page, route or data input changes, or use an Error Boundary library that supports reset keys and reset callbacks.

9. Using Error Boundaries with React Router

In applications with multiple routes, it is useful to handle rendering errors at the route level.

React Router provides route error handling through its errorElement option when using a data router.

Example:

import {
  createBrowserRouter,
  RouterProvider
} from "react-router-dom";
import HomePage from "./HomePage";
import ProductsPage from "./ProductsPage";
import RouteErrorPage from "./RouteErrorPage";
const router = createBrowserRouter([
  {
    path: "/",
    element: <HomePage />,
    errorElement: <RouteErrorPage />
  },
  {
    path: "/products",
    element: <ProductsPage />,
    errorElement: <RouteErrorPage />
  }
]);
function App() {
  return <RouterProvider router={router} />;
}
export default App;

RouteErrorPage.jsx:

import { useRouteError } from "react-router-dom";
function RouteErrorPage() {
  const error = useRouteError();
  return (
    <div>
      <h2>Unable to load this page.</h2>
      <p>Please try again later.</p>
    </div>
  );
}
export default RouteErrorPage;

React Router's route error handling can catch errors from route rendering, loaders and actions. It is not identical to a general-purpose React Error Boundary, so choose the appropriate mechanism for the type of error.

10. What Errors Do Error Boundaries Catch?

Error Boundaries catch errors in their descendant component tree during React rendering and certain React lifecycle operations.

Error TypeCaught by Error Boundary?
Error during component renderingYes
Error in a descendant lifecycle methodYes
Error in a descendant constructorYes, subject to boundary placement
Error inside an event handlerNo
Error inside setTimeout callbackNo
Error inside Promise rejectionNo
Error during server-side renderingNo, not through client Error Boundaries

Important: Error Boundaries do not catch every JavaScript error. Event handlers, asynchronous callbacks and Promise rejections need their own error handling.

11. How to Handle Errors in Event Handlers

Errors inside event handlers are not automatically caught by Error Boundaries.

Use try/catch to handle errors explicitly.

Example:

function SaveButton() {
  async function handleSave() {
    try {
      const response = await fetch("/api/save", {
        method: "POST"
      });
      if (!response.ok) {
        throw new Error("Unable to save data");
      }
      console.log("Data saved successfully");
    } catch (error) {
      console.error("Save failed:", error);
    }
  }
  return (
    <button onClick={handleSave}>
      Save
    </button>
  );
}

Here, try/catch handles the asynchronous operation. The Error Boundary does not automatically catch errors from this event handler.

12. Error Boundaries vs API Error Handling

It is important to understand that API errors and rendering errors are different.

FeatureError BoundaryAPI Error Handling
PurposeHandles errors in React component renderingHandles failed API requests and responses
Typical errorsRendering exceptionsNetwork failures, HTTP errors
Handling mechanismReact Error Boundarytry/catch, query error states
FallbackFallback component UIError message, retry button

Example:

If the product API returns an HTTP 500 response, handle that failure in the API or data-fetching layer and display an appropriate error message.

If the ProductList component itself throws an exception while rendering the response, an Error Boundary can catch that rendering error.

13. Logging Errors to Monitoring Services

In production applications, logging errors only to the browser console is not sufficient.

We should capture useful information and send it to an appropriate monitoring service.

Examples of monitoring services include:

  • Sentry
  • Azure Application Insights
  • Datadog
  • New Relic

Example integration point:

componentDidCatch(error, errorInfo) {
  console.error("React error:", error);
  // Send the error and component information
  // to your configured monitoring service.
}

Useful information to capture includes:

  • Error message.
  • Component stack.
  • Application version.
  • Route or page information.
  • Relevant non-sensitive diagnostic context.

Security note: Avoid sending passwords, access tokens, payment information or other sensitive user data to error monitoring systems.

14. Common Mistakes to Avoid

  1. Using only one Error Boundary for everything: Independent sections may need separate boundaries.
  2. Expecting Error Boundaries to catch API errors automatically: Handle failed requests in the data-fetching layer.
  3. Expecting Error Boundaries to catch event handler errors: Use try/catch inside event handlers.
  4. Showing technical error details to users: Display friendly messages instead.
  5. Not providing recovery options: Consider retry or navigation options where appropriate.
  6. Ignoring error logging: Capture errors for production debugging.
  7. Assuming retry always fixes the problem: Resetting a boundary does not repair the underlying error.
  8. Placing the boundary incorrectly: A boundary cannot catch errors thrown by itself or its fallback UI.

15. Recommended Error Boundary Architecture

For a medium or large React application, use multiple levels of error handling.

Layer 1 Application Root Error Boundary App Fallback UI If root fails Application Layout Header Routes Footer Dashboard Products Widget Boundary Sales Widget Widget Boundary Reports Widget Feature Boundary Product List Widget Fallback UI Widget Fallback UI Feature Fallback UI Sales failure isolated Reports failure isolated Products failure isolated

Recommended responsibilities:

  • Root Error Boundary: Handles unexpected rendering failures across the application.
  • Route-level error handling: Displays an appropriate page when route rendering, loaders or actions fail.
  • Feature-level Error Boundaries: Protect independent application sections and widgets.
  • API error handling: Handles failed network requests and unsuccessful HTTP responses.
  • Monitoring: Captures errors for investigation and improvement.

16. Interview Questions and Answers

Q1. What is an Error Boundary in React?

An Error Boundary is a React component that catches errors in its descendant component tree during rendering and displays a fallback UI instead of allowing the affected component tree to fail.

Q2. Which lifecycle methods are used to create Error Boundaries?

getDerivedStateFromError() updates state to display fallback UI, while componentDidCatch() receives error details and can be used for logging.

Q3. Can we create Error Boundaries using functional components?

React does not provide a built-in Hook for creating Error Boundaries. The standard implementation uses a class component. Libraries can provide reusable alternatives with a simpler API.

Q4. Do Error Boundaries catch errors in event handlers?

No. Errors in event handlers should be handled using try/catch or other appropriate error-handling mechanisms.

Q5. Can Error Boundaries catch API errors?

They do not automatically catch asynchronous API failures. API errors should be handled in the API service, try/catch block or data-fetching library.

Q6. Why should we use multiple Error Boundaries?

Multiple boundaries isolate failures. If one independent section fails, other sections can continue working.

Q7. What is the purpose of getDerivedStateFromError()?

It updates the Error Boundary state after a descendant rendering error so that React can display fallback UI.

Q8. What is the purpose of componentDidCatch()?

It receives the error and component stack information. It is commonly used to log errors to monitoring services.

Q9. Can an Error Boundary catch errors inside itself?

No. An Error Boundary cannot catch errors thrown by itself or its fallback UI. An outer Error Boundary may catch those errors.

Q10. How do you implement Error Boundaries in a production application?

Use a root boundary, feature-level boundaries, route-level error handling where appropriate, API error handling, user-friendly fallback interfaces and centralized error monitoring.

17. Final Takeaways

  • Error Boundaries protect React component trees from rendering failures.
  • Use getDerivedStateFromError() to display fallback UI.
  • Use componentDidCatch() to capture error details.
  • Place boundaries around independent application sections.
  • Use try/catch for event handlers and asynchronous operations.
  • Handle API failures separately from rendering failures.
  • Provide retry or recovery options where appropriate.
  • Use monitoring services to investigate production errors.

Most important principle: Design Error Boundaries to isolate failures. A problem in one feature should not unnecessarily prevent users from accessing other working parts of the application.

🔙
How to Manage State Across Multiple Pages :👈 👉:How to Organize a Large React Codebase

Comments and Discussion