React 16 introduced a lot of interesting features into the React ecosystem. One of them was handling errors by creating boundaries for only that component. This feature prevents the whole app from crashing if there is an error in only one of the child components by creating boundaries around that component.
More information about the announcement here.
Earlier, whenever there was an error in the React component, the whole app would crash and there would be no way to prevent that. With React 16, it’s possible to create boundaries around your app so that if anything within that boundary errors out, you can show a fallback interface in its place and send the report to an online client.
Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
Suppose, we have a component called Ability:
Now, we want to create an Error Boundary around that component. We can simply modify our component like:
The ErrorBoundary component looks like the following:
Let’s take a look at this component and understand what it does. We have the componentDidCatch lifecycle hook, which is responsible for catching any errors for any inbound components during rendering, in lifecycle methods, and in constructors of the whole tree below them. In that hook, we are setting a flag called hasError to true. Also, you can send the error to any online reporting service here.
In the render method, we are using the hasError flag to show the fallback interface if we have an error. Otherwise, we will just render the children, which is the Ability component here. Please note that we have the following component structure in our app:
Consider the following as the usual interface of our very simple app:
Now, let’s look at the situation when we encounter an error in our app.
If we don’t create an ErrorBoundary, our app will look something like the following when it crashes:
There is no going back from this state and our users should never encounter a page like this. Whereas, if we use an error boundary, it will look something like the following:
This is much better than the previous situation. Here, we could also put some navigation which will take us to our home page or any relevant page. Also, if we are sure that our app will work fine on refresh, we could show a timer and then refresh the page.
The fallback interface is much better since it handles an error case in our app and we can send a report to any online client and track it there.
The example app is available on Github. Feel free to check it out. The readme of the repository will give you an idea about how to make the example app work on your system.