Dealing with Errors like a pro in React.js

Dealing with Errors like a pro in React.js

Introduction

We have all encountered errors while building our react application. Errors that will always break our application. And then, when we check our console for the type of error, we see something like this

How do we Deal with Ugly Errors Like this?

  1. By Using Error Boundaries

One of the ways to deal with breaking errors in our react application is to use Mr. Error Boundary.

Error Boundaries in React are React Components, that catch errors within our application, log these errors and display a fallback UI. In this scenario, the application does not crash but instead, it renders a new UI where when it encounters an error.

How to use Error Boundaries

Using Error boundaries to take care of our errors is quite easy. First, let us create a React Component and name it ErrorBoundary.tsx.

ErrorBoundary.tsx

import React, { Component } from 'react'

type ErrorProps = {}
export default class ErrorComponent extends Component<Error, {errorPresent: boolean}> {
    constructor(props: any) {
        super(props);
        this.state = { errorPresent: false }

    }

    static getDerivedStateFromError(error) {
        return { errorPresent: true }
    }

    compoenentDidCatch(){

    }

    render() {
        if (this.state.hasError) {
            return( <p>Something went wrong</p>)
        }
        return (<>
            { this.props.children }
        </>)
    }
}

From the code above, we used a class-based approach to write our Error Boundary component instead and not the functional-based approach. Currently, there is no way to write Error Boundaries as a functional component.

  1. By using react-error-boundary

    react-error-boundary is a simple reusable React Error Boundary Component.

How to use react-error-boundary

Run npm install react-error-boundary to install the package.

This is a Simple example of how to use react-error-boundary.

import { ErrorBoundary } from "react-error-boundary";

function fallbackRender({ error, resetErrorBoundary }) {
  // Call resetErrorBoundary() to reset the error boundary and retry the render.

  return (
    <div>
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
    </div>
  );
}

<ErrorBoundary
  fallbackRender={fallbackRender}
  onReset={(details) => {
    // Reset the state of your app so the error doesn't happen again
  }}
>
  <MyApplication/>
</ErrorBoundary>;

Conclusion

In conclusion, Error Boundary does not catch errors with the following:

  • Asynchronous code

  • Event Handlers

  • Server-side rendering

To do this, you can use the react-error-boundary package.

Finally, we have been able to learn how to handle errors in React.js like pros.