Diego Betto's Blog
Photo by Markus Spiske on Unsplash

July 17, 2024 · 3 min di lettura

How Error Boundaries work in React, with examples

How Error Boundaries work in React: components that catch errors from their children to improve your app's stability and reliability.

Condividi:XLinkedInFacebookWhatsApp

In a React application, errors aren’t just annoying — they can bring down the entire application, damaging the user experience in the process. To address this, React introduces the concept of Error Boundaries.

Error Boundaries are special components that act as error catchers for the components beneath them. When an error occurs inside a child component, React looks for the closest Error Boundary in the component tree and triggers its componentDidCatch method to handle the error.

How Error Boundaries work

An Error Boundary is a class-based React component that implements the componentDidCatch method. This method is called when an error occurs inside the component itself or one of its child components. Inside componentDidCatch, you can log the error, update the component’s state, and display a fallback UI in place of the component that threw the error.

Error Boundary example

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

  componentDidCatch(error, info) {
    console.error("Error:", error);
    this.setState({ error });
  }

  render() {
    const { error } = this.state;
    if (error) {
      return (
        <div>
          <h1>Something went wrong!</h1>
          <p>Error message: {error.message}</p>
        </div>
      );
    }

    return this.props.children;
  }
}

In this example, the Error Boundary logs the error to the console and updates the component’s state with the error object. The render method then checks the error state and, if present, displays a fallback UI in place of the child component.

Benefits of Error Boundaries

Error Boundaries offer several benefits:

  • They prevent the application from crashing: by isolating the error inside the Error Boundary, you prevent the entire application from going down.
  • They improve the user experience: by displaying a fallback UI, you give the user a more pleasant experience than a bare application crash.
  • They make debugging easier: by logging the error and providing useful information, Error Boundaries make debugging the application easier.

Use cases for Error Boundaries

Error Boundaries can be used in various situations:

  • Critical components: protect critical parts of the application from errors that could cause serious problems.
  • Third-party components: wrap third-party components you don’t fully control, so errors inside them don’t crash the whole application.
  • Experimental sections: protect experimental parts of the application from errors that haven’t been fully tested yet.

The “react-error-boundary” package

react-error-boundary

is a popular npm package that simplifies creating error boundaries in React. It provides a reusable component that can be wrapped around other components to catch errors and display a custom fallback UI.

Main features of react-error-boundary

  • Catches JavaScript errors: catches errors that occur in child components, preventing the whole application from crashing.
  • Displays a fallback UI: lets you customize the UI shown when an error occurs, providing a better user experience.
  • Logs errors: lets you log caught errors for later analysis and debugging.
  • Supports different fallback modes: offers several options for displaying the fallback UI, such as plain text, React components, or external URLs.

Usage examples for react-error-boundary

Here’s an example of how to use react-error-boundary to wrap a component and display a generic error message when an error occurs:

import React from "react";
import ErrorBoundary from "react-error-boundary";

const MyComponent = () => {
  return (
    <ErrorBoundary>
      <MyComponent />
    </ErrorBoundary>
  );
};

In this example, if an error occurs inside the MyComponent component, the error boundary will display a generic error message in its place.

You can also customize the fallback UI using a React component. For example, the following code displays an ErrorFallback component when an error occurs:

import React from "react";
import ErrorBoundary from "react-error-boundary";
import ErrorFallback from "./ErrorFallback";

const MyComponent = () => {
  return (
    <ErrorBoundary FallbackComponent={ErrorFallback}>
      <MyComponent />
    </ErrorBoundary>
  );
};

Conclusion

Error Boundaries are a valuable tool for handling errors in React. They help prevent application crashes, improve the user experience, and make debugging easier. I’d recommend using Error Boundaries in every React application to ensure greater stability and reliability.

Happy coding 😉

Condividi:XLinkedInFacebookWhatsApp