Recognized by Clutch.co as a top-rated Mobile App Development Company.
folio3-mobile
US 408 365 4638
START YOUR PROJECT
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise
    • AR/VR
    • IoT
    • Wearables
    • Field Sales
    • On Demand Apps
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical & Life Sciences
    • Manufacturing
    • Automotive
    • Logistics
    • Education
  • Technologies
    • Native Mobile Apps
      • iOS
      • Android
    • Cross Platform Apps
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • Sencha
  • Portfolio
  • Blog
  • Contact Us
Menu
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise
    • AR/VR
    • IoT
    • Wearables
    • Field Sales
    • On Demand Apps
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical & Life Sciences
    • Manufacturing
    • Automotive
    • Logistics
    • Education
  • Technologies
    • Native Mobile Apps
      • iOS
      • Android
    • Cross Platform Apps
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • Sencha
  • Portfolio
  • Blog
  • Contact Us

Error Boundary in React Native

Published by: Muhammad Hur Ali | April 21, 2022 msaqlain
SCROLL AND BE AMAZED!
Home > React Native > Error Boundary in React Native

Users hate it the most when they are using their app and they are presented with a white screen or suddenly an “App keeps closing” popup comes up. So how do we tackle this, how can we try to make the user experience a bit better than this frustrating one? That’s where ErrorBoundary comes in. ErrorBoundary is an API provided by React but it is more of a concept than an actual API. So what it says is that you create a HOC that implements the componentDidCatch lifecycle to grab the error that’s gonna crash the app, and also the getDrivedStateFromError which decides the state that we can use to display a fallback UI instead of the creepy white screen or the crash popup. Also, the componentDidCatch can be used to report the error to the Error Logging service.

With our understanding ready about the ErrorBoundary, let’s see how to use it:

We will first create a fresh react-native app in TypeScript:

npx react-native init ErrorBoundaryDemo --template react-native-template-typescript

And install react-native-restart, so when our app crashes we display them a good sorry message and an option to retry, and we then restart our app.

Next, we run the app to see if all is good. Now we need to create ErrorBoundary HOC, so we will create a folder hierarchy like src/components/error-boundary/index.tsx

import React, {ErrorInfo, ReactNode} from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';
import RNRestart from 'react-native-restart';
 
interface Props {
 children: ReactNode;
}
 
interface State {
 hasError: boolean;
}
 
class ErrorBoundary extends React.Component<Props, State> {
 constructor(props: Props) {
   super(props);
   this.state = {hasError: false};
 }
 
 static getDerivedStateFromError(_: Error): State {
   // Update state so the next render will show the fallback UI.
   return {hasError: true};
 }
 
 componentDidCatch(error: Error, errorInfo: ErrorInfo) {
   // You can also log the error to an error reporting service
   console.log('componentDidCatch ', error, ' ', errorInfo);
 }
 
 render() {
   if (this.state.hasError) {
     // You can render any custom fallback UI
     return (
       <View style={styles.container}>
         <Text style={styles.message}>
           Something went wrong.{'\n'} Our team has taken a note of this issue.
         </Text>
         <Button title="Try Again" onPress={() => RNRestart.Restart()} />
       </View>
     );
   }
 
   return this.props.children;
 }
}
 
export default ErrorBoundary;
 
const styles = StyleSheet.create({
 container: {
   flex: 1,
   justifyContent: 'center',
   alignItems: 'center',
 },
 message: {
   fontSize: 16,
   marginBottom: 20,
   textAlign: 'center',
   paddingHorizontal: 10,
 },
});

As we have already discussed, the componentDidCatch will be called whenever the underlying tree crashes. So we can use it to register the crash to an error reporting service. Also, the getDerivedStateFromError gives us the state update that we can use to display the fallback UI. We can use beautiful Lottie animations here, but for the sake of simplicity, I haven’t added them.

Also, let’s create this home screen in src/screens/home-screen/index.tsx, so it looks like this.

import React from 'react';
import {Text, View, StyleSheet} from 'react-native';
 
interface IHomeScreenProps {}
 
const userData = {
 email: '[email protected]',
 name: 'Hur Ali',
};
 
const HomeScreen = (_: IHomeScreenProps) => {
 return (
   <View style={styles.container}>
     <Text>Home Screen</Text>
     <Text>User Email: {userData.email}</Text>
     <Text>User Name: {userData.name}</Text>
   </View>
 );
};
 
export default HomeScreen;
 
const styles = StyleSheet.create({
 container: {
   alignItems: 'center',
   paddingTop: 20,
   flex: 1,
 },
});

After that, update your App.tsx with the following code as we clean out the old boilerplate:

import React from 'react';
import {
 SafeAreaView,
 StatusBar,
 StyleSheet,
 useColorScheme,
} from 'react-native';
 
import {Colors} from 'react-native/Libraries/NewAppScreen';
import ErrorBoundary from './src/components/error-boundary';
import HomeScreen from './src/screens/home-screen';
 
const App = () => {
 const isDarkMode = useColorScheme() === 'dark';
 
 const backgroundStyle = {
   backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
   flex: 1,
 };
 
 return (
   <SafeAreaView style={backgroundStyle}>
     <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
     <ErrorBoundary>
       <HomeScreen />
     </ErrorBoundary>
   </SafeAreaView>
 );
};
 
const styles = StyleSheet.create({});
 
export default App;

So, what we’ve done is that we wrapped our HomeScreen inside of ErrorBoundary. Practically, we will be placing the whole app container here which is the Navigation.

Now run your app and see if everything is good. Okay, so now we want to test it. So whenever something causes a crash in the rendering, our ErrorBoundary will handle it by displaying the fallback UI.

So we will add a console.log(userDat) statement in the HomeScreen before the return statement. Since userDat doesn’t exist, this JS error will cause the crash. If you save it now, you’ll be shown with the red error screen, since it’s in debug mode. But if you dismiss the screen, our FallbackUI will be shown. This red Error screen won’t appear in the release mode, hence the user will be directly shown the fallback UI. 

That’s all. For more information, please refer to the following references.

For reference:

https://reactjs.org/docs/error-boundaries.html#:~:text=Error%20boundaries%20are%20React%20components,the%20whole%20tree%20below%20them

https://github.com/mhurali-folio/ErrorBoundaryDemo


About Muhammad Hur Ali

Newsletter

Search

Archives

  • April 2023
  • March 2023
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • October 2021
  • September 2021
  • May 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019
  • May 2019

Recent Posts

  • Web UI Test Automation with Pytest-BDD
  • How to fix IOS compass calibration issues
  • Testing Android Applications With Perfect Coverage
  • How to use useRef hook efficiently? – React
  • Introduction To Full Stack Quality Assurance

Tags

  • android
  • angular-state-management
  • Automation
  • Compass
  • cross-platform
  • css
  • development
  • firebase
  • hooks
  • ios
  • learn-ngrx
  • ngrx-beginner
  • ngrx/store
  • QA
  • react-native
  • reactjs
  • scss
  • stylesheet
  • styling
  • Testing
  • Test Script
  • UI-UX

Newsletter

Newsletter

Post navigation

Previous Speech to Text Recognition in React Native
Next Introduction to Nessus Vulnerability Scanning Tool
Schedule an appointment with our Mobile App Development Expert

    Footer Menu
    • Company
      • About Us
      • Portfolio
      • Blog
      • Careers
      • Contact Us
    • Solutions
      • Apps Discovery Services
      • Team Augmentation
      • Enterprise App Development
      • AR/VR Application Development
      • IoT Application Development
      • Wearables Apps Development
      • Field Sales
      • On-Demand Apps Development
    • Technologies
      • iOS
      • Android
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • HTML5
      • Sencha
    • Industries
      • Retail
      • Agriculture
      • Healthcare
      • Pharmaceutical
      • Manufacturing
      • Automotive
      • Logistics
      • Education

    US Office

    Belmont, California – 1301 Shoreway Road, Suite 160, Belmont, CA 94002

    Pleasanton, California – 6701 Koll Center Parkway, #250 Pleasanton, CA 94566

    Tel: +1 408 365 4638
    Support: +1 (408) 512 1812

    Mexico Office

    Amado Nervo #2200, Edificio Esfera 1 piso 4, Col. Jardines del Sol, CP. 45050, Zapopan, Jalisco, Mexico

    Bulgaria Office

    49 Bacho Kiro Street, Sofia, 1000, Bulgaria

    Canada Office​

    895 Don Mills Road, Two Morneau Shepell Centre, Suite 900, Toronto, Ontario, M3C 1W3, Canada

    UK Office

    Export House, Cawsey Way, Woking Surrey, GU21 6QX

    Tel: +44 (0) 14 8361 6611

    UAE Office

    Dubai, UAE – Dubai Internet City, 1st Floor, Building Number 12, Premises ED 29, Dubai, UAE

    Tel: +971-55-6540154
    Tel: +971-04-2505173

    Pakistan Office

    163 Bangalore Town, Main Shahrah-e-Faisal, Karachi –
    75350

    705, Business Center, PECHS Block-6, Shahrah-e-Faisal,
    Karachi – 75350

    First Floor, Blue Mall 8-R, MM Alam Road Gulberg III, Lahore

    Tel: +92-21-3432 3721-4 

    © 2021, Folio3 Software Inc., All rights reserved.

    • Privacy policy and terms of use
    • Cookie Policy
    Follow us on
    Facebook-f Twitter Linkedin-in

    Get a free app audit

      Tired of your app not performing up to the mark?

      Get a free technology and app strategy review.