React Native: Working with Error Boundaries

How to integrate and test error boundaries to gracefully contain errors in React Native apps

Ross Bulat

--

Error boundaries act as fallback UI when errors occur

When used with React Native, error boundaries allow you to implement fallback screens at certain points in your app that will be displayed when a JavaScript error occurs at runtime as a means to notify the user something went wrong. These fallback screens can then give the user a friendly explanation that something indeed went wrong, as well as an opportunity to restart the app or reset the UX to a previous state.

The following screencast demonstrates an error boundary in action simulated from a development build of an app I personally develop. This error boundary wraps the entire app and therefore responds to errors originating from any component in the hierarchy. An exception is thrown when I switch from the Settings tab to the Plans tab. This results in the fallback UI — defined in an ErrorBoundary component — being displayed. From here, the user can tap a button to restart the app, that also deletes user settings and other persisted state that may have caused the error:

Testing an error boundary in a release build in iOS Simulator

This exception was deliberately thrown for demonstration purposes (the app generally speaking is very stable!) using throw , that can be placed within a particular component:

throw new Error('Testing error boundary');

Error boundaries help apps “save face” when things go wrong, but are also integral to the app experience: in the event they are not implemented, the entire app would crash resulting in the user leaving it completely and guessing what went wrong in the process. This may even deter users from using your app again. Error boundaries are a simple solution to avoid such a scenario, and provide a means to keep the user in-app.

It is common to wrap an entire component hierarchy in an error boundary component, but it is also possible to wrap individual sections of your app in Error Boundaries to replace a certain part…

--

--

Ross Bulat

Programmer and Author. @ Parity Technologies, JKRB Investments