DEV Community

Siddhartha Khare for New Relic

Posted on

Optimizing React Native app performance

To read this full New Relic article, click here


React Native is an open-source framework developed by Facebook that enables developers to build mobile applications for iOS, Android, and other platforms using JavaScript and React. React Native allows developers to create native-like apps with a high level of performance while writing most of their codebase in JavaScript, which is familiar to many web developers. React Native uses native components under the hood instead of rendering WebViews like hybrid frameworks, resulting in a better user experience and smoother interactions.

In the complicated arena of mobile application development, it's the responsibility of product managers and developers to design applications that not only provide impeccable functionality but also provide exceptional performance and a compelling user experience. Comprehensive performance monitoring is essential for accomplishing these demanding goals. By continuously monitoring the app's performance, teams may effectively discover and resolve any underlying issues that may adversely affect the app's overall performance, ensuring that users experience nothing less than excellence.

How to get started

Increase the speed of your React Native app analysis and gain valuable insights in under 10 minutes.

  • Install React Native agent.

New Relic provides an SDK (aka the React Native agent) for your application instrumentation.
To install the SDK, follow these steps:

  • Add the SDK agent.

Using Yarn:

yarn add newrelic-react-native-agent
Enter fullscreen mode Exit fullscreen mode

Using NPM:

npm i newrelic-react-native-agent
Enter fullscreen mode Exit fullscreen mode
  • Initialize React Native agent. In index.js add the following code to launch New Relic:
import NewRelic from 'newrelic-react-native-agent';
import {name, version} from './package.json';
import {Platform} from 'react-native';

    let appToken;

    if (Platform.OS === 'ios') {
        appToken = '<IOS-APP-TOKEN>';
    } else {
        appToken = '<ANDROID-APP-TOKEN>';
    }

 const agentConfiguration = {

    //Android Specific
    // Optional:Enable or disable collection of event data.
    analyticsEventEnabled: true,

    // Optional:Enable or disable crash reporting.
    crashReportingEnabled: true,

    // Optional:Enable or disable interaction tracing. Trace instrumentation still occurs, but no traces are harvested. This will disable default and custom interactions.
    interactionTracingEnabled: true,

    // Optional:Enable or disable reporting successful HTTP requests to the MobileRequest event type.
    networkRequestEnabled: true,

    // Optional:Enable or disable reporting network and HTTP request errors to the MobileRequestError event type.
    networkErrorRequestEnabled: true,

    // Optional:Enable or disable capture of HTTP response bodies for HTTP error traces, and MobileRequestError events.
    httpRequestBodyCaptureEnabled: true,

   // Optional:Enable or disable agent logging.
    loggingEnabled: true,

    // Optional:Specifies the log level. Omit this field for the default log level.
    // Options include: ERROR (least verbose), WARNING, INFO, VERBOSE, AUDIT (most verbose).
    logLevel: NewRelic.LogLevel.INFO,

    // iOS Specific
    // Optional:Enable/Disable automatic instrumentation of WebViews
    webViewInstrumentation: true,

    // Optional:Set a specific collector address for sending data. Omit this field for default address.
    // collectorAddress: "",

    // Optional:Set a specific crash collector address for sending crashes. Omit this field for default address.
    // crashCollectorAddress: "",

    // Optional:Enable or disable reporting data using different endpoints for US government clients
    // fedRampEnabled: false
  };


NewRelic.startAgent(appToken,agentConfiguration);
NewRelic.setJSAppVersion(version);
AppRegistry.registerComponent(name, () => App);
Enter fullscreen mode Exit fullscreen mode

Note: Don’t forget to put the proper application token(s) for Android and iOS applications.

npx pod-install
Enter fullscreen mode Exit fullscreen mode
  • Link the New Relic library to your React Native project and rebuild the application. React Native 0.60+ includes “autolinking” for seamless integration.

    • Android applications autolinking:
       npx react-native run-android
    
    • iOS applications autolinking:
       cd ios/ 
       pod install –-repo-update
       cd ..
       npx react-native run-ios
    
  • Verify React Native app’s proper function by executing below commands. Fatal JavaScript errors will be visible as crashes in New Relic UI.

npx react-native run-android --variant=release
Enter fullscreen mode Exit fullscreen mode
npx react-native run-ios --configuration Release
Enter fullscreen mode Exit fullscreen mode

After instrumenting your React Native app, you can gather key mobile telemetry data, such as crashes, HTTP requests, failures, and events. Use New Relic analytics to improve your app's speed and UX. Here are few reasons why it's helpful:

  • Data-backed decisions

Performance monitoring tools provide deeper insights into problems faced by users. Visualize significant information on user-friendly dashboards, set alerts to refer problems to relevant features, and proactively manage issues.

  • JavaScript error insight

The Handled Exceptions page in New Relic reveals JavaScript failures and promise rejections. It displays event trails, attributes, and stack traces for each JavaScript error that has been gathered.

Use the following query to access these errors, allowing you to create a dashboard for cohesive visualization.

SELECT * FROM MobileHandledException SINCE 24 hours ago

SELECT JSAppVersion, JSEngine, name, exceptionMessage, exceptionCause, isFatal FROM MobileHandledException SINCE 7 DAYS AGO limit MAX
Enter fullscreen mode Exit fullscreen mode

Handled Exception Summary

  • ANR detection and capture

Application not responding (ANR) situations are an unpleasant problem with users that often end up in negative app reviews and ratings. Leading ANR causes include timed-out input dispatch and long-running operations on the main thread.

The native agent detects ANR events efficiently, pointing out situations where activities or service threads are obstructed above Android's allowable level. For foreground activities, this threshold is 5 seconds, and for services, it ranges from 5 to 200 seconds. ANR situations, unlike crashes, are reported as handled exceptions.

  • Spotting rooted devices

Manufacturers restrict devices for safety reasons, while rooted devices provide administrators complete OS control. A rooted smartphone grants you extra privileges and allows you to customize it, but it can also signal disaster. Some of the potential issues linked with rooted devices include security breaches, data loss, and so on.

ANR and Rooted Device Detection

  • Breadcrumbs

Breadcrumbs are a simplified form of session logging that collects metadata throughout a session and transmits it all at once at the end of the session. This approach minimizes the burden on the device's CPU and RAM, avoids separate network calls, and has no impact on the app's performance. Breadcrumbs can be used to debug crashes, provide insights into user behavior, and track user journeys.

To use breadcrumbs, add this code to your project:

​​NewRelic.recordBreadcrumb("Start Download Image",{"imageColor":"blue"});
Enter fullscreen mode Exit fullscreen mode

For more details on how to use this method, see Record breadcrumbs.

Once you’ve recorded breadcrumbs, you’ll see them in crash analysis in the UI.

Recorded Breadcrumb

  • Service maps

Service maps are interactive graphical representations of your architecture. These dynamic maps depict detailed relationships and dependencies within the application, comprising critical pieces like databases, hosts, servers, and external services.

Graphical representation of your application

  • Unveiling memory exhaustion incidents

You can use the New Relic agent to monitor out of memory (OOM) errors, which are caused by insufficient memory. These errors frequently confuse users because they see it as an abrupt app shutdown, similar to a crash. This degrades the user experience, which may result in app abandonment or unfavorable ratings

Out-of-Memory Exceptions

  • Crash reports

This provides insights about the crash happening, including:

  • Granular device and OS breakdown
  • App version analytics
  • Occurence enumeration
  • User impact assessment
  • Sequentially delineated crash-related interactions and events
  • Curated subsets of incidents

Crash Summary

Crash Stack Trace

Conclusion

Monitoring React Native mobile applications is more than just a requirement; it is a beneficial, proactive approach. Building an app is merely the first engagement. Your applications achieve a distinctive advantage within a competitive market landscape, potentially enhancing overall business outcomes, through methodical performance monitoring, preemptive issue resolution, and strategic user engagement optimization.

Read the full blog post at New Relic: Optimizing React Native app performance

Not an existing New Relic user? Sign up for a free account to get started! 👨‍💻

Top comments (0)