React Error Boundaries
For simple React app, we can declare an error boundary once and can use it for the whole application. For a complex application which have multiple components, we can declare multiple error boundaries to recover each part of the entire application.
We can also report the error to an error monitoring service like Rollbar. This monitoring service provides the ability to track how many users are affected by errors, find causes of them, and improve the user experience.
Error boundary in class
A class component can becomes an error boundary if it defines a new lifecycle methods either static getDerivedStateFromError() or componentDidCatch(error, info). We can use static getDerivedStateFromError() to render a fallback UI when an error has been thrown, and can use componentDidCatch() to log error information.
How to implement error boundaries
Step-1 Create a class which extends React component and passes the props inside it.
Step-2 Now, add componentDidCatch() method which allows you to catch error in the components below them in the tree.
Step-3 Next add render() method, which is responsible for how the component should be rendered. For example, it will display the error message like "Something is wrong."
Step-4 Now, we can use it as a regular component. Add the new component in HTML, which you want to include in the error boundary. In this example, we are adding an error boundary around a MyWidgetCounter component.
Where to Place Error Boundaries
An error boundary entirely depends on you. You can use error boundaries on the top-level of the app components or wrap it on the individual components to protect them from breaking the other parts of the app.
Let us see an example.
First, these two counters are inside the same error boundary. If anyone crashes, the error boundary will replace both of them.
Second, these two counters are inside of their individual error boundary. So if anyone crashes, the other is not affected.
When we execute the above code, we will get the following output.
When the counter has reached at 3, it gives the following output.
New Behavior for Uncaught error
It is an important implication related to error boundaries. If the error does not catch by any error boundary, it will result in unmounting of the whole React application.
Error Boundary in Event Handler
In the below example, you can see how an event handler will handle the errors.