DEV Community

Michael Lefkowitz
Michael Lefkowitz

Posted on • Edited on

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


`

Top comments (3)

Collapse
 
jeongsd profile image
jeong seong dae • Edited

Great article thank you!

Collapse
 
pavermakov profile image
Pavel Ermakov

Does this work with native errors?

Collapse
 
lfkwtz profile image
Michael Lefkowitz

nope, but this may help you