DEV Community

Michael Lefkowitz
Michael Lefkowitz

Posted on • Edited on

7 2

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


`

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay