React Error Boundary
Tags: react, errorboundary, javascript, errors
Published: 2023-02-28 15:01:11

React Error Boundaries are a feature introduced in React that allows you to catch errors that occur during rendering, in life cycle methods, and in constructors of the entire component tree. With error boundaries, you can prevent an error from crashing the entire application and instead, display a fallback UI. Error boundaries are currently only supported as class components in React, so if you're using hooks, you may need to include a class component for error handling.

Error Boundaries work by wrapping the components that you want to monitor for errors. When an error occurs within one of these components or any of its descendants, the Error Boundary component catches the error and displays a fallback UI instead of the crashed component tree.

To catch errors during rendering, wrap the component you want to handle errors with an Error Boundary component. Here is an example:

```
<ErrorBoundary errorComponent={ClientError}>
                <Component {...pageProps} />
              </ErrorBoundary>
```


In this example, if an error occurs during rendering , the Error Boundary component will catch the error and display the fallback UI instead.

```
import React, { Component, ErrorInfo } from "react";

interface ErrorBoundaryProps {
  errorComponent: () => JSX.Element;
  children: React.ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = {
      hasError: false,
    };
  }

  static getDerivedStateFromError(error: unknown) {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    //TODO: Integrate Datadog
    console.error("Error Boundary Caught an error: ", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <this.props.errorComponent />;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

```

In the example above,there is a React component called ErrorBoundary. Its purpose is to catch any errors that occur within its child components and display a fallback UI instead of the crashed component tree.

The ErrorBoundary class has two interfaces. The **ErrorBoundaryProps** interface defines the props that ErrorBoundary accepts, which includes an errorComponent prop and a children prop. The **ErrorBoundaryState** interface defines the state of the ErrorBoundary, which is whether or not an error has occurred.

The ErrorBoundary class has a constructor that initializes the state to _hasError: false._

The ErrorBoundary class also has two methods to handle errors. The static **getDerivedStateFromError()**method is called when an error is thrown from any of its child components. It returns an object that updates the state of the ErrorBoundary to indicate that an error has occurred.

The **componentDidCatch()** method is called after an error is thrown from any of its child components. In this method, the developer can add any code necessary to handle the error, such as logging or reporting the error to an external service. In this code snippet, the method logs the error and errorInfo to the console.

Finally, the render() method checks if an error has occurred by looking at the hasError state. If an error has occurred, it renders the errorComponent that was passed in as a prop. If no error has occurred, it renders its children prop, which is the child component tree that it is wrapping.

This component is very useful for catching errors in production environments.It’s generally advisable to use at least one Error Boundary at the root of your app (e.g., the App.js file). This will prevent users from seeing a blank HTML page and perhaps see a nice/custom fallback UI instead.

Remember, just like in life, sometimes things can go wrong in our React applications too. But with the ErrorBoundary, we can catch those errors and make sure they don't bring the whole house down! So go ahead and wrap your components with an ErrorBoundary, and rest assured that even if your code throws some shade, your application will keep on shining!;)