React recommends using an error boundary to provide a better user experience when an error occurs.

What Is the Error Boundary Class in React?

Error boundaries work like the try/catch block in vanilla JavaScript. The difference is that they catch the errors that occur in React components. If an error occurs in a UI component, React unmounts the tree within that component and replaces it with the fallback UI you have defined. This means that an error only affects the component in which it occurs and the rest of the application works as expected.

According to the React documentation, error boundary classes do not catch errors in:

Event handlers. Asynchronous code. Server-side code. Errors thrown in the error boundary itself (rather than its children).

For the above errors, you can use the try/catch block.

For example, to catch an error that occurs in the event handler, use the following code:

Use error boundaries to catch errors in React components only.

Creating an Error Boundary Class

You can create an error boundary by defining a class that contains one or both of the following methods:

static getDerivedStateFromError() componentDidCatch()

The getDerivedStateFromError() function updates the component state once the error is caught while you can use componentDidCatch() to log error information to the console. You can also send the errors to an error reporting service.

Below is an example showing how to create a simple error boundary class.

When an error occurs, getDerivedStateFromError() will update the state and consequently trigger a re-render that will display the fallback UI.

If you don’t want to create the error boundary class from scratch, use the react-error-boundary NPM package. This package provides the ErrorBoundary component that wraps around components you think might raise errors.

Using the Error Boundary Class

To handle errors, wrap components with the error boundary class component. You can wrap the top-level component or individual components.

If you wrap the top-level component, the error boundary class will handle the errors thrown by all the components in the React application.

If you wrap an individual component with an ErrorBoundary, an error in that component will not affect how another component renders.

For example, an error in the profile component will not affect how another component like the Hero component renders. While the profile component may crash, the rest of the application will work fine. This is much better than rendering the generic white fallback screen provided by React.

Handling Errors in JavaScript

Programming errors can be frustrating for developers and users. Failing to handle errors can expose your users to ugly UI with hard-to-understand error messages.

When building your React component, create an error boundary class either from scratch or using the react-error-boundary package to display user-friendly error messages.