Date:

Handling Crashes & Logging Errors to Firebase in React Native

Why Use react-native-error-boundary?

Using react-native-error-boundary is crucial for improving user experience and debugging. This guide will cover how to use react-native-error-boundary to catch errors and send crash logs to Firebase Analytics.

Why Use react-native-error-boundary?

  1. Catches uncaught JavaScript errors and prevents app crashes.
  2. Displays a custom fallback UI instead of a blank screen.
  3. Helps in tracking and debugging errors efficiently.

Install Dependencies

First, install the required dependencies:

npm install react-native-error-boundary @react-native-firebase/app @react-native-firebase/analytics

Create a Global Error Boundary Component

This component will wrap the entire app and catch unhandled JavaScript errors.

Create a Global Error Boundary Component

AppErrorBoundary.js

import React from 'react';
import { View, Text, Button } from 'react-native';
import ErrorBoundary from 'react-native-error-boundary';
import analytics from '@react-native-firebase/analytics';
import { logErrorToFirebase } from './logErrorToFirebase';

const AppErrorBoundary = () => {
  return (
    <ErrorBoundary
      FallbackComponent={() => (
        <View>
          <Text>Something went wrong!</Text>
          <Button title="Try Again" onPress={() => console.log('Try Again')} />
        </View>
      )}
    >
      {children}
    </ErrorBoundary>
  );
};

export default AppErrorBoundary;

Wrap the App with Error Boundary

Now, wrap your main app component with AppErrorBoundary in App.js.

App.js

import React from 'react';
import { View, Text } from 'react-native';
import { AppErrorBoundary } from './AppErrorBoundary';

const App = () => {
  return (
    <AppErrorBoundary>
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Welcome to the App!</Text>
      </View>
    </AppErrorBoundary>
  );
};

export default App;

What Happens When an Error Occurs?

Without Error Boundary: The app crashes and closes unexpectedly.

With react-native-error-boundary:

  • The error is caught and logged to Firebase Analytics.
  • A friendly UI is shown to users instead of a blank screen.
  • Users can recover using a “Try Again” button.

Viewing Firebase Analytics Logs

To check error logs in Firebase:

  1. Go to Firebase Console → Analytics.
  2. Click on Events → Look for "app_crash".
  3. View error messages and stack traces.

Conclusion

By integrating react-native-error-boundary with Firebase Analytics, you:

  • Prevent app crashes from unhandled JavaScript errors.
  • Log detailed crash reports to Firebase for debugging.
  • Show a user-friendly fallback UI to prevent app disruption.

Would you like to extend this by sending logs to Sentry or Crashlytics as well? Let me know!

Latest stories

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here