React Error Boundary: A Guide to Gracefully Handling Errors
Tags: javascript, react, typescript, webdev
Published: 2024-05-13 03:30:00

React revolves around JavaScript, and as the application expands, certain components may become error-prone, leading to a blank page problem. To tackle this, we should incorporate Error Boundaries. These boundaries will display an alternative UI when an error occurs, allowing the user to navigate back or retry. This article will explore how we can gracefully handle errors in React by using error boundaries.

## What is an error boundary?

Think of error boundaries in React as safety nets. They're like guardians watching over a group of performers (the components) on a stage (the app). If any performer falls down **(a JavaScript error occurs)**, the safety net (the error boundary) catches them. It then logs what happened and puts up a poster (the fallback UI) until the performer is ready to get back on stage.

## Implementing Error Boundaries in React

React supports two types of components: class-based and functional components. However, if we want to implement an error boundary, we can't do it with a functional component; we need to create a class-based component for the error boundary. But don't worry, the React community is extensive, and many third-party packages are available to help you use a React error boundary component directly instead of creating it yourself.

We will use the `react-error-boundary` package, which provides an ErrorBoundary component that catches errors and displays the fallback UI. It offers various methods to show the fallback UI.

Let's begin by installing the `react-error-boundary` as a dependency in our React project.

```bash
yarn add react-error-boundary

OR

npm install react-error-boundary

OR

pnpm add react-error-boundary
```

After installing the dependency, create the fallback component that you want to display when an error occurs.

```typescript
import React from "react";
import { FallbackProps } from "react-error-boundary";
import ErrorFallbackIcon from "./error-fallback.svg";

const ErrorFallback: React.FC<FallbackProps> = ({
  error,
  resetErrorBoundary,
}) => {
  return (
    <div className="error-boundary-fallback-wrapper">
      <ErrorFallbackIcon />
      <h1>Something went wrong</h1>
      <p>{error.message}</p>
      <button onClick={resetErrorBoundary}>Home</button>
    </div>
  );
};

export default ErrorFallback;
```

The fallback component accepts two props.

* `error` : error object that contains the error message.
    
* `resetErrorBoundary` : a callback function to reset the error boundary and retry rendering.
    

Alright, we have the fallback component ready. Now, let's wrap our application with the `ErrorBoundary` component provided by `react-error-boundary`.

```typescript
import React from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { useHistory } from 'react-router-dom';
import ErrorFallback from './ErrorFallback';

interface Props {
  children: React.ReactNode;
}

const App: React.FC<Props> = ({ children }) => {
  const history = useHistory();

  const handleErrorReset = () => {
    history.push("/");
  };

  return (
    <ErrorBoundary FallbackComponent={ErrorFallback} onReset={handleErrorReset}>
      {children}
    </ErrorBoundary>
  );
};

export default App;
```

The `ErrorBoundary` component accepts several props, but the important ones are:

* `FallbackComponent` : Fallback component to render when an error occurs.
    
* `onReset` : callback function to reset the state of the application so that the error doesn't happen again.
    

Okay, our application is now wrapped with an error boundary. As a regular user, if you interact with the application and encounter an error on a specific page causing a crash, instead of seeing a blank page, you will be directed to a fallback page. This page will display the exact error message and provide you with the option to navigate back.

![error-fallback-ui](https://cdn.hashnode.com/res/hashnode/image/upload/v1715486165963/863247b7-d670-40cb-8104-05f5c77f110e.png)

## Conclusion

Implementing error boundaries in React using the `react-error-boundary` package can help in gracefully handling errors and providing a fallback UI for users when errors occur. By incorporating error boundaries, developers can ensure a better user experience by preventing blank pages and offering options to navigate back or retry.

That's all for this topic. Thank you for reading! If you found this article helpful, please consider liking, commenting, and sharing it with others.

## Resources

* [Official doc](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
    
* [React Error Boundary npm](https://www.npmjs.com/package/react-error-boundary)
    

## **Connect with me**

* [**LinkedIn**](https://www.linkedin.com/in/sachin-chaurasiya)
    
* [**Twitter**](https://twitter.com/sachindotcom)
    
* [**GitHub**](https://github.com/Sachin-chaurasiya)