Introduction

Let's take a look at how to catch errors anywhere in the component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

We'll cover the following

What are Error Boundaries?

Whenever an error occurs, and an exception is thrown in a React application, there is a strong possibility that the application display no longer works and that the user will only see a blank page. To avoid this behavior, React introduced error boundaries in version 16.0.

An error boundary describes a component that can catch certain errors in its children and can also render an alternative component tree to protect users from experiencing a blank page. Error boundaries always serve as a parent component of a component tree. If an exception is thrown in the component tree, the error boundary can intercept and handle the error. Try and think of error boundaries as a special form of a try/catch block for component hierarchies.

They can deal with mistakes that result from handling of the following situations:

  • Errors in lifecycle methods
  • Errors in the render() method anywhere inside the Error Boundary
  • Errors in the constructor() of a component

If React encounters an error in a lifecycle method, the render() method, or in the constructor of a component, the error boundary can safely prevent it. It will display a fallback that will prompt the user to restart their application or inform them that something has gone wrong. Similar to Context components, error boundaries can be nested inside each other. If an error occurs, the implementation of the higher error boundary component takes precedence.

Note: The primary goal of error boundaries is to prevent and deal with errors caused when handling user interfaces that would otherwise prevent further rendering of the application status. Error boundaries were not intended for implementing from validation and should not be used for this.


Limitations

There are certain situations in which error boundaries do not work in:

  • Event handlers
  • Asynchronous code (like setTimeOut() or requestAnimationFrame())
  • SSR:Server-side rendered #key# components
  • Errors which occur in the Error Boundary itself

Error boundaries will not work in these situations as it is either unnecessary or impossible for them to deal with the problem at hand. If an event-handler throws an error, this might not necessarily impact its render, and React can continue to show a working interface to the user. The only repercussion would be the missing interaction based on the said event.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy