Error Boundaries In React

Error Boundaries In React

ยท

2 min read

Well hello! ๐Ÿ‘‹ Let me give you some flashback of your favorite screen which you might have encountered while building of your React application

image.png

Looks pretty familiar doesn't it ?

Well to be honest, we all have have been here at some point of time, and after few enhancement we are able to remove the error and get back to the desired screen.

But that might not be the case when you face an unexpected error in production build of your application.

Unlike the crashed component tree which we see in development mode, the production build only gives a blank screen which may end up confusing the user what went wrong or what needs to be done next ? Something like this ๐Ÿ‘‡

image.png

Well to eliminate such last minute surprises, the concept of Error Boundaries comes in handy.

What are Error Boundaries In React ?

Error Boundaries are React components which help us to catch Javascript errors encountered throughout the application and gracefully handle them by logging the error properly along with displaying a fallback UI.

They catch errors not just from the initial render, from anywhere inside lifecycle methods as well as from any constructors in the tree below them..

Note : Error Boundaries do not catch errors for:

  • Event handlers
  • Asynchronous Code (setTimeout or other callbacks)
  • Server side rendering
  • Errors thrown in the error boundary itself

How to implement Error Boundaries in your application ?

As of React 18, Error Boundaries can only be achieved in class based components, and if you are not a big fan of class-based component, you need not worry too.

react-error-boundary package is your way out!

The simplest way to use <ErrorBoundary> is to wrap it around any component that may throw an error. This will handle errors thrown by that component and its descendants too.

Let's see a quick demo shall we!

Note : You will be still seeing the error stack trace in the example since it's in dev mode, in order to view the fallback UI just press ESC

The simplest way to use is to wrap it around any component that may throw an error. This will handle errors thrown by that component and its descendants too.

image.png

ย