Site icon Mobile App Development Services

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: 'mhurali@folio3.com',
 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