Home Reactjs React Error Boundaries: Know How to Install it All

React Error Boundaries: Know How to Install it All

0
851
React Error Boundaries

An Introduction About React Error Boundaries

Often in the past days, errors inside JavaScript components used to corrupt the internal state of React. As a result of it cause to emit cryptic errors on the subsequent renders. The main cause of these errors was an earlier error that occurred in the code of the application. However, React did not provide a graceful way to handle them in components and couldn’t even recover them.

An error in JavaScript in some parts of the UI should not hamper the working of the whole app. In order to solve this issue, a new concept was introduced by React 16 called an “error boundary. Error boundaries are React components that can catch errors anywhere inside tree of child components. It identifies and keeps track of those errors, and instead of displaying component tree that crashed, it displays fallback UI. In lifecycle methods, errors are caught by error boundaries and inside the constructor in the whole tree that is present below them.

However, error boundaries can not catch the errors for the following:

  1. Event handlers
  2. Server side rendering
  3. Asynchronous code for instance: setTimeout or requestAnimationFrame callbacks
  4. Errors thrown in error boundaries itself (rather than its children)

 If a class component defines both the lifecycle methods like that of static getDerivedStateFromError() or componentDidCatch() then it becomes an error boundary. In order to render a fallback UI after an error has already been thrown, we use static getDerivedStateFromError(). Also, in order to check in to the error information, we use componentDidCatch().

So it can be used as a regular component:

Error boundaries work the same as that of a JavaScript catch{} block except that it works only for the components. However, only the class components can become error boundaries. Most of the time you’ll find yourself needing to declare an error boundary component which you will use throughout application.  Not to mention that error boundaries can catch only those errors in the components that are below the item in the tree.  Nonetheless, an error boundary can not catch an error within itself. So, you can see how it’s working is similar to that of catch{} block in JavaScript. 

Installation of Modules Containing Error Boundaries

 

The module containing error boundaries is distributed via npm which has got abundant of nodes which we should install as one of our project dependencies:

npm install –save react-error-boundary

 

Where do React Error Boundaries Need to be Placed?

The coarseness of error boundaries is up to the developer of the application. We may wrap the route components at the top level. It displays an “ An error has occurred” message for the user, . It is just like that of frameworks from server-side that handle crashes. Developers also wrap individual widgets inside of an error boundary to protect them from crashing rest of application.

Why not try/catch?

There’s so no doubt that try/catch is absolutely great but it only works for codes that are imperative.

The components in React are declarative in nature and specify what is needed to be rendered:

<Button />

It is safe to say that React boundaries save and preserve the declarative nature of React. It also behave as expected by the developers. For instance: Even if the program comes across any errors in a componentDidUpdate method caused by a which is caused by a setState somewhere situated very deep in a tree, it is still going to propagate the error boundary closest to it.

Without Error Boundaries:

The fact that we are always going to encounter unexpected errors in our apps, is inevitable. It might be possible that we are trying to access a property deeply nested on an object that doesn’t exist. Sometimes it is also possible that sometimes it will not be our control. Without the error boundaries, what happens when the app encounters an error? When it happens, the component completely unmounts itself and the user is left with a blank HTML page. Error boundaries provide us with a way of handling these errors very gracefully. 

With Error Boundaries:

React encourages us to think in terms of components. It is quite evident to us application developers that an app composed of multiple smaller components. Working in this way really helps us to think about our application as simple small units. Besides that fact, it would be really nice if we could contain the errors that can happen in any of the components. A single failure should not result in the crashing of the whole application and React makes sure that you never have to face such a scenario through React Error Boundaries.

For us to know what great things are possible with React boundaries, it is important to know what exactly React Error Boundaries exactly are. If you are thinking that it is a new component or JavaScript library, then it is exactly contrary to what you think. Instead, what it actually is is a strategy for handling errors in the React Components. In React Error Boundaries, there is specific usage of two methods that is available to us in the React Components. So while we are talking about it, we should have knowledge of what these lifecycle methods are.

What are the two Lifecycle Methods?

  1. static getDerivedStateFromError: This is a lifecycle method which allows the Error Boundary to get a chance in updating the state and thereby triggering a last render(). If we take an example, the state that is being used to give a more human-friendly error message instead of the broken component is exactly this state.
  2. componentDidCatch: It is a lifecycle method used for triggering the side effects. For example logging the errors to certain tools like Crashlytics and we can access the info.componentStack for getting a developer-friendly stack trace that will be extremely useful in triggering any bugs that are present in the code so that they can be taken care of beforehand.

 

Error Boundaries and Try/Catch

The error boundaries are never in direct competition with the try/catch statements. They are designed for intercepting the errors that have their origin from three particular places in React Component. Those places are:

  1. During the render phase
  2. In a lifecycle method
  3. In a constructor

These are basically the react -y parts of a component and as a counterpoint, we can say that these are the places where the error boundaries will not be able to catch any error.

  1. The event handlers that are there, for example, onClick, onCharge, etc
  2. setTimeout or the requestAnimationFramecallback
  3. Server-side rendering (SSR)
  4. The errors due to error boundary itself rather than the children it has.

Conclusion

If as a developer you haven’t been using error boundaries in your React applications, you should immediately consider adding one at the topmost level of the code of your React app. Also, it is quite recommendable to integrate an error reporting service into your project so that people coming across any error can get back at you and report the issue. Thus, this component provides us with a reusable as well as a simple wrapper class that we can use to wrap it around your various components so that any rendering error that occurs in your hierarchy of components can be easily handled.

 

No Comments

Leave A Reply

Please enter your comment!
Please enter your name here