Handle React Native crashes with the componentDidCatch error boundary

lfkwtz

Michael Lefkowitz

Posted on September 3, 2018

Handle React Native crashes with the componentDidCatch error boundary

Want to stay up-to-date? Check out React Native Now, the bi-weekly React Native newsletter


React 16 allows you to catch JavaScript errors inside of your components, which is great if you're aware of a particular component that is prone to break for one reason or another. As an added measure of protection, you can also utilize error boundaries in our top level parent with a componentDidCatch so that your users can have a better experience if an unexpected error occurs in any of the children/screens.

In the below example, I utilize a native alert combined with the react-native-restart package to provide users with an easy way to reboot the app and recover from a crash.

componentDidCatch(error, info) {
    // to prevent this alert blocking your view of a red screen while developing
    if (__DEV__) {
        return;
    }

    // to prevent multiple alerts shown to your users
    if (this.errorShown) {
        return;
    }

    this.errorShown = true;

    Alert.alert(
        null,
        'An unexpected error has occurred. Please restart to continue.',
        [
            {
                text: buttonText,
                onPress: RNRestart.Restart,
            },
        ],
        { cancelable: false }
    );
}
Enter fullscreen mode Exit fullscreen mode


`

💖 💪 🙅 🚩
lfkwtz
Michael Lefkowitz

Posted on September 3, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related