Analytics for React Native

Community x
Maintenance x
Flagship ✓
?

Flagship libraries offer the most up-to-date functionality on Segment’s most popular platforms. Segment actively maintains flagship libraries, which benefit from new feature releases and ongoing development and support.


With Analytics for React Native, you can collect analytics in your React Native application and send data to any analytics or marketing tool without having to learn, test, or implement a new API every time. Analytics React Native enables you to process and track the history of a payload, while Segment controls the API and prevents unintended operations.

All of Segment’s libraries are open-source, and you can view Analytics for React Native on GitHub. For more information, see the Analytics React Native GitHub repository.

Using Analytics for React Native Classic?

As of May 15, 2023, Segment ended support for Analytics React Native Classic, which includes versions 1.5.1 and older. Use the implementation guide to upgrade to the latest version.

@segment/analytics-react-native is compatible with Expo’s Custom Dev Client and EAS builds without any additional configuration. Destination Plugins that require native modules may require custom Expo Config Plugins.

@segment/analytics-react-native isn’t compatible with Expo Go.

Getting Started

To get started with the Analytics for React Native library:

  1. Create a React Native Source in Segment.
    1. Go to Connections > Sources > Add Source.
    2. Search for React Native and click Add source.
  2. Install @segment/analytics-react-native, @segment/sovran-react-native and react-native-get-random-values. You can install in one of two ways:

     yarn add @segment/analytics-react-native @segment/sovran-react-native react-native-get-random-values
    

    or

     npm install --save @segment/analytics-react-native @segment/sovran-react-native react-native-get-random-values
    
  3. If you want to use the default persistor for the Segment Analytics client, you also have to install react-native-async-storage/async-storage. You can install in one of two ways:

     yarn add @react-native-async-storage/async-storage 
    

    or

     npm install --save @react-native-async-storage/async-storage
    

    To use your own persistence layer you can use the storePersistor option when initializing the client. Make sure you always have a persistor (either by having AsyncStorage package installed or by explicitly passing a value), else you might get unexpected side effects like multiple ‘Application Installed’ events

  4. If you’re using iOS, install native modules with:

     npx pod-install
    
  5. If you’re using Android, you need to add extra permissions to your AndroidManifest.xml.

     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
  6. Initialize and configure the Analytics React Native client. The package exposes a method called createClient which you can use to create the Segment Analytics client. This central client manages all the tracking events.

     import { createClient, AnalyticsProvider } from '@segment/analytics-react-native';
    
     const segmentClient = createClient({
       writeKey: 'SEGMENT_API_KEY'
     });
    

These are the options you can apply to configure the client:

Name Default Description
writeKey required ’’ Your Segment API key.
collectDeviceId false Set to true to automatically collect the device Id.from the DRM API on Android devices.
debug true* When set to false, it will not generate any logs.
logger undefined Custom logger instance to expose internal Segment client logging.
flushAt 20 How many events to accumulate before sending events to the backend.
flushInterval 30 In seconds, how often to send events to the backend.
flushPolicies undefined Add more granular control for when to flush, see Adding or removing policies
maxBatchSize 1000 How many events to send to the API at once
trackAppLifecycleEvents false Enable automatic tracking for app lifecycle events: application installed, opened, updated, backgrounded
trackDeepLinks false Enable automatic tracking for when the user opens the app with a deep link. This requires additional setup on iOS, see instructions
defaultSettings undefined Settings that will be used if the request to get the settings from Segment fails. Type: SegmentAPISettings
autoAddSegmentDestination true Set to false to skip adding the SegmentDestination plugin
storePersistor undefined A custom persistor for the store that analytics-react-native uses. Must match Persistor interface exported from sovran-react-native.
proxy undefined proxy is a batch url to post to instead of ‘https://api.segment.io/v1/b’.
errorHandler undefined Create custom actions when errors happen, see Handling errors

Adding Plugins to the Client

You can add a plugin at any time through the segmentClient.add() method. More information about plugins, including a detailed architecture overview and a guide to creating your own can be found here.

import { createClient } from '@segment/analytics-react-native';

import { AmplitudeSessionPlugin } from '@segment/analytics-react-native-plugin-amplitude-session';
import { FirebasePlugin } from '@segment/analytics-react-native-plugin-firebase';
import { IdfaPlugin } from '@segment/analytics-react-native-plugin-idfa';

const segmentClient = createClient({
  writeKey: 'SEGMENT_KEY'
});

segmentClient.add({ plugin: new AmplitudeSessionPlugin() });
segmentClient.add({ plugin: new FirebasePlugin() });
segmentClient.add({ plugin: new IdfaPlugin() });

Usage

You can use Analytics React Native with or without hooks. Detailed overviews of both implementation options can be found below.

Usage with hooks

To use the useAnalytics hook within the application, wrap the application in an AnalyticsProvider. This uses the Context API which allows access to the analytics client anywhere in the application.

import {
  createClient,
  AnalyticsProvider,
} from '@segment/analytics-react-native';

const segmentClient = createClient({
  writeKey: 'SEGMENT_API_KEY'
});

const App = () => (
  <AnalyticsProvider client={segmentClient}>
    <Content />
  </AnalyticsProvider>
);

The useAnalytics() hook exposes the client methods:

import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import { useAnalytics } from '@segment/analytics-react-native';

const Button = () => {
  const { track } = useAnalytics();
  return (
    <TouchableOpacity
      style={styles.button}
      onPress={() => {
        track('Awesome event');
      }}
    >
      <Text style={styles.text}>Press me!</Text>
    </TouchableOpacity>
  );
};

Usage without hooks

To use the tracking events without hooks, call the methods directly on the client:

import {
  createClient,
  AnalyticsProvider,
} from '@segment/analytics-react-native';

// create the client once when the app loads
const segmentClient = createClient({
  writeKey: 'SEGMENT_API_KEY'
});

// track an event using the client instance
segmentClient.track('Awesome event');
track: (event: string, properties?: JsonMap) => void;
const { track } = useAnalytics();

track('View Product', {
  productId: 123,
  productName: 'Striped trousers',
});

Core tracking methods

Once you’ve installed the Analytics React Native library, you can start collecting data through Segment’s tracking methods:

Destinations

Destinations are the business tools or apps that Segment forwards your data to. Adding Destinations allow you to act on your data and learn more about your customers in real time.


Segment offers support for two different types of Destinations, learn more about the differences between the two here.

Tools and extensions

group: (groupId: string, groupTraits?: JsonMap) => void;
const { group } = useAnalytics();

group('some-company', {
  name: 'Segment',
});

Utility Methods

The Analytics React Native 2.0 utility methods help you to manage your data. They include:

  • Alias
  • Reset
  • Flush
  • Cleanup

Alias

The alias method is used to merge two user identities by connecting two sets of user data as one. This method is required to manage user identities in some of Segment’s destinations.

alias: (newUserId: string) => void;
const { alias } = useAnalytics();

alias('user-123');

Reset

The reset method clears the internal state of the library for the current user and group. This is useful for apps where users can log in and out with different identities over time.

Note: Each time you call reset, a new AnonymousId is generated automatically.

reset: () => void;
const { reset } = useAnalytics();

reset();

The reset method doesn't clear the `userId` from connected client-side integrations. If you want to clear the `userId` from connected client-side destination plugins, you'll need to call the equivalent reset method for that library.

Flush

By default, the analytics client sends queued events to the API every 30 seconds or when 20 events accumulate, whichever occurs first. This also occurs whenever the app resumes if the user has closed the app with some events unsent. These values can be modified by the flushAt and flushInterval config options. You can also trigger a flush event manually.

flush: () => Promise<void>;
const { flush } = useAnalytics();

flush();

Cleanup

In case you need to reinitialize the client, that is, you’ve called createClient more than once for the same client in your application lifecycle, use this method on the old client to clear any subscriptions and timers first.

let client = createClient({
  writeKey: 'KEY'
});

client.cleanup();

client = createClient({
  writeKey: 'KEY'
});

If you don’t do this, the old client instance would still exist and retain the timers, making all your events fire twice.

Ideally, you shouldn’t have to use this method, and the Segment client should be initialized only once in the application lifecycle.

Control upload with Flush Policies

To granularly control when Segment uploads events you can use FlushPolicies. A Flush Policy defines the strategy for deciding when to flush. This can be on an interval, time of day, after receiving a certain number of events, or after receiving a particular event. This gives you more flexibility on when to send event to Segment. Set Flush Policies in the configuration of the client:

const client = createClient({
  // ...
  flushPolicies: [
    new CountFlushPolicy(5),
    new TimerFlushPolicy(500),
    new StartupFlushPolicy(),
  ],
});

You can set several policies at a time. When a flush occurs, it triggers an upload of the events, then resets the logic after every flush. As a result, only the first policy to reach shouldFlush will trigger a flush. In the example above either the event count reaches 5 or the timer reaches 500ms, whatever comes first will trigger a flush. Segment has several standard Flush Policies:

  • CountFlushPolicy triggers when you reach a certain number of events
  • TimerFlushPolicy triggers on an interval of milliseconds
  • StartupFlushPolicy triggers on client startup only

If you implement custom flush policies, they replace Segment’s default Count and Timer policies. To incorporate custom policies, add your custom Timer and Count policies to the client’s Flush Policies configuration.

Adding or removing policies

One of the main advantages of Flush Policies is that you can add and remove policies on the fly. This is very powerful when you want to reduce or increase the amount of flushes. For example you might want to disable flushes if you detect the user has no network:

import NetInfo from "@react-native-community/netinfo";
const policiesIfNetworkIsUp = [
  new CountFlushPolicy(5),
  new TimerFlushPolicy(500),
];
// Create our client with our policies by default
const client = createClient({
  // ...
  flushPolicies: [...policiesIfNetworkIsUp],
});
// If Segment detects the user disconnect from the network, Segment removes all flush policies. 
// That way the Segment client won't keep attempting to send events to Segment but will still 
// store them for future upload.
// If the network comes back up, the Segment client adds the policies back. 
const unsubscribe = NetInfo.addEventListener((state) => {
  if (state.isConnected) {
    client.addFlushPolicy(...policiesIfNetworkIsUp);
  } else {
    client.removeFlushPolicy(...policiesIfNetworkIsUp)
  }
});

Creating your own flush policies

You can create a custom Flush Policy special for your application needs by implementing the FlushPolicy interface. You can also extend the FlushPolicyBase class that already creates and handles the shouldFlush value reset. A FlushPolicy only needs to implement two methods:

  • start(): Executed when the flush policy is enabled and added to the client. This is a good place to start background operations, make async calls, configure things before execution
  • onEvent(event: SegmentEvent): Called on every event tracked by your client
  • reset(): Called after a flush is triggered (either by your policy, by another policy, or manually) Your policies also have a shouldFlush observable boolean value. When this is set to true the client attempts to upload events. Each policy should reset this value to false according to its own logic, although it’s common to do it inside the reset method.
    export class FlushOnScreenEventsPolicy extends FlushPolicyBase {
    onEvent(event: SegmentEvent): void {
      // Only flush when a screen even happens
      if (event.type === EventType.ScreenEvent) {
        this.shouldFlush.value = true;
      }
    }
    reset(): void {
      // Superclass will reset the shouldFlush value so that the next screen event triggers a flush again
      // But you can also reset the value whenever, say another event comes in or after a timeout
      super.reset();
    }
    }
    

Automatic screen tracking

As sending a screen() event with each navigation action can get tiresome, it’s best to track navigation globally. The implementation is different depending on which library you use for navigation. The two main navigation libraries for React Native are React Navigation and React Native Navigation.

React Navigation

When setting up React Navigation, you’ll essentially find the root level navigation container and call screen() whenever the user navigates to a new screen. Segment’s example app is set up with screen tracking using React Navigation, so you can use it as a guide.

To set up automatic screen tracking with React Navigation:

  1. Find the file where you used the NavigationContainer. This is the main top level container for React Navigation.
  2. In the component, create a new state variable to store the current route name:

     const [routeName, setRouteName] = useState('Unknown');
    
  3. Create a utility function for determining the name of the selected route outside of the component:

       const getActiveRouteName = (
         state: NavigationState | PartialState<NavigationState> | undefined
       ): string => {
         if (!state || typeof state.index !== 'number') {
           return 'Unknown';
         }
    
         const route = state.routes[state.index];
    
         if (route.state) {
           return getActiveRouteName(route.state);
         }
    
         return route.name;
       };
    
  4. Pass a function in the onStateChange prop of your NavigationContainer that checks for the active route name and calls client.screen() if the route has changes. You can pass in any additional screen parameters as the second argument for screen calls as needed.

     <NavigationContainer
     onStateChange={(state) => {
       const newRouteName = getActiveRouteName(state);
    
       if (routeName !== newRouteName) {
         segmentClient.screen(newRouteName);
         setRouteName(newRouteName);
       }
     }}
     >
    

React Native Navigation

In order to set up automatic screen tracking while using React Native Navigation:

  1. Use an event listener at the point where you set up the root of your application (for example, Navigation.setRoot).
  2. Access your SegmentClient at the root of your application.

       // Register the event listener for *registerComponentDidAppearListener*
       Navigation.events().registerComponentDidAppearListener(({ componentName }) => {
         segmentClient.screen(componentName);
       });
    

Plugin Architecture

Segment’s plugin architecture enables you to modify and augment how the events are processed before they’re uploaded to the Segment API. In order to customize what happens after an event is created, you can create and place various Plugins along the processing pipeline that an event goes through. This pipeline is referred to as a timeline.

Plugin Types

Plugin Type Description
before Executes before event processing begins.
enrichment Executes as the first level of event processing.
destination Executes as events begin to pass off to destinations.
after Executes after all event processing is completed. You can use this to perform cleanup operations.
utility Executes only with manual calls such as Logging.

Plugins can have their own native code (such as the iOS-only IdfaPlugin or wrap an underlying library (such as the FirebasePlugin which uses react-native-firebase under the hood).

Destination Plugins

Segment is an out-of-the-box DestinationPlugin. You can add as many other destination plugins as you like and upload events and data to them.

If you don’t want the Segment destination plugin, you can pass autoAddSegmentDestination = false in the options when setting up your client. This prevents the SegmentDestination plugin from being added automatically for you.

Adding Plugins

You can add a plugin at any time through the segmentClient.add() method.


import { createClient } from '@segment/analytics-react-native';

import { AmplitudeSessionPlugin } from '@segment/analytics-react-native-plugin-amplitude';
import { FirebasePlugin } from '@segment/analytics-react-native-plugin-firebase';
import { IdfaPlugin } from '@segment/analytics-react-native-plugin-idfa';

const segmentClient = createClient({
  writeKey: 'SEGMENT_KEY'
});

segmentClient.add({ plugin: new AmplitudeSessionPlugin() });
segmentClient.add({ plugin: new FirebasePlugin() });
segmentClient.add({ plugin: new IdfaPlugin() });

Writing your own Plugins

Plugins implement as ES6 Classes. To get started, familiarize yourself with the available classes in /packages/core/src/plugin.ts.

The available plugin classes are:

  • Plugin
  • EventPlugin
  • DestinationPlugin
  • UtilityPlugin
  • PlatformPlugin

Any plugin must be an extension of one of these classes. You can then customize the functionality by overriding different methods on the base class. For example, here is a simple Logger plugin:

// logger.js

import {
  Plugin,
  PluginType,
  SegmentEvent,
} from '@segment/analytics-react-native';

export class Logger extends Plugin {

  // Note that `type` is set as a class property
  // If you do not set a type your plugin will be a `utility` plugin (see Plugin Types above)
  type = PluginType.before;

  execute(event: SegmentEvent) {
    console.log(event);
    return event;
  }
}
// app.js

import { Logger } from './logger';

segmentClient.add({ plugin: new Logger() });

As the plugin overrides the execute() method, this Logger calls console.log for every event going through the Timeline.

Add a custom Destination Plugin

You can add custom plugins to Destination Plugins. For example, you could implement the following logic to send events to Braze on weekends only:


import { createClient } from '@segment/analytics-react-native';

import {BrazePlugin} from '@segment/analytics-react-native-plugin-braze';
import {BrazeEventPlugin} from './BrazeEventPlugin';

const segmentClient = createClient({
  writeKey: 'SEGMENT_KEY'
});

const brazeplugin = new BrazePlugin();
const myBrazeEventPlugin = new BrazeEventPlugin();
brazeplugin.add(myBrazeEventPlugin);
segmentClient.add({plugin: brazeplugin});

// Plugin code for BrazeEventPlugin.ts
import {
  Plugin,
  PluginType,
  SegmentEvent,
} from '@segment/analytics-react-native';

export class BrazeEventPlugin extends Plugin {
  type = PluginType.before;

  execute(event: SegmentEvent) {
    var today = new Date();
    if (today.getDay() === 6 || today.getDay() === 0) {
      return event;
    }
  }
}

Segment would then send events to the Braze Destination Plugin on Saturdays and Sundays, based on device time.

Example Plugins

These are the example plugins you can use and alter to meet your tracking needs:

Plugin Package
Adjust @segment/analytics-react-native-plugin-adjust
Amplitude Sessions @segment/analytics-react-native-plugin-amplitude-session
AppsFlyer @segment/analytics-react-native-plugin-appsflyer
Braze @segment/analytics-react-native-plugin-braze
Consent Manager @segment/analytics-react-native-plugin-adjust
Facebook App Events @segment/analytics-react-native-plugin-facebook-app-events
Firebase @segment/analytics-react-native-plugin-consent-firebase
IDFA @segment/analytics-react-native-plugin-idfa

Supported Destinations

Segment supports a large number of Cloud-mode destinations. Segment also supports the below destinations for Analytics React Native 2.0 in device-mode, with more to follow:

Device identifiers

On Android, Segment’s React Native library generates a unique ID by using the DRM API as context.device.id. Some destinations rely on this field being the Android ID, so be sure to double-check the destination’s vendor documentation. If you choose to override the default value using a plugin, make sure the identifier you choose complies with Google’s User Data Policy. For iOS the context.device.id is set the IDFV.

To collect the Android Advertising ID provided by Play Services, Segment provides a plugin that can be used to collect that value. This value is set to context.device.advertisingId. For iOS, this plugin can be used to set the IDFA context.device.advertisingId property.

FAQs

Can I use the catalog of device-mode destinations from Segment’s 1.X.X React-Native release?

No, only the plugins listed above are supported in device-mode for Analytics React Native 2.0.

Will I still see device-mode integrations listed as false in the integrations object?

When you successfully package a plugin in device-mode, you won’t see the integration listed as false in the integrations object for a Segment event. This logic is packaged in the event metadata, and isn’t surfaced in the Segment debugger.

Why are my IDs not set in UUID format?

Due to limitations with the React Native bridge, Segment doesn’t use UUID format for anonymousId and messageId values in local development. These IDs will be set in UUID format for your live app.

How do I set a distinct writeKey for iOS and android?

You can set different writeKeys for iOS and Android. This is helpful if you want to send data to different destinations based on the client side platform. To set different writeKeys, you can dynamically set the writeKey when you initialize the Segment client:

import {Platform} from 'react-native';
import { createClient } from '@segment/analytics-react-native';

const segmentWriteKey = Platform.iOS ? 'ios-writekey' : 'android-writekey';

const segmentClient = createClient({
  writeKey: segmentWriteKey
});

What is the instanceId set in context?

The instanceId was introduced in V 2.10.1 and correlates events to a particular instance of the client in a scenario when you might have multiple instances on a single app.

How do I interact with the integrations object?

The integrations object is no longer part of the Segment events method signature. To access the integrations object and control what destinations the event reaches, you can use a Plugin:

import {
    EventType,
    Plugin,
    PluginType,
    SegmentEvent,
  } from '@segment/analytics-react-native';
  
  export class Modify extends Plugin {
    type = PluginType.before;
  
    async execute(event: SegmentEvent) {
      if (event.type == EventType.TrackEvent) {
        let integrations = event.integrations;
        if (integrations !== undefined) {
          integrations['Appboy'] = false;
        }
      }
      //console.log(event);
      return event;
    }
  }

How do I add to the context Object?

Like with the integrations object above, you’ll need to use a plugin to access and modify the context object. For example, if you’d like to add context.groupId to every Track call, you should create a plugin like this:

//in AddToContextPlugin.js
import {
  Plugin,
  PluginType,
  SegmentEvent,
} from '@segment/analytics-react-native';

export class AddToContextPlugin extends Plugin {
  // Note that `type` is set as a class property
  // If you do not set a type your plugin will be a `utility` plugin (see Plugin Types above)
  type = PluginType.enrichment;

 async execute(event: SegmentEvent) {
    if (event.type == EventType.TrackEvent) {
      event.context['groupId'] = 'test - 6/8'
      }
      return event;
    }
}
 // in App.js

import { AddToContextPlugin } from './AddToContextPlugin'

segmentClient.add({ plugin: new AddToContextPlugin() });  

I’ve upgraded to React Native 2.0, but I am still getting warnings in the Google Play Store that my app is not compliant. Why is this?

The React Native 2.0 library is compliant with Google Play Store policies. However, Segment recommends that you check to see if there are any old and inactive tracks on the Google Play Store that are not updated to the latest build. If this is the case, we recommend updating those tracks to resolve the issue.

Can I set inlineRequires to false in my metro.config.js file?

Segment requires the inlineRequires value in your metro.config.js value to be set to true. To disable inlineRequires for certain modules, you can specify this by using a blockList.

Can I clear user traits without calling the reset() method?

The set method on userInfo can accept a function that receives the current state and returns a modified desired state. Using this method, you can return the current traits, delete any traits you no longer wish to track, and persist the new trait set.

segmentClient.userInfo.set((currentUserInfo) => {
  return {
    ...currentUserInfo, 
    traits: {
        // All the traits except the one you want to delete
       persistentTrait: currentUserInfo.persistentTrait
    }
  });

If I use a proxy, what Segment endpoint should I send to?

If you proxy your events through the proxy config option, you must forward the batched events to https://api.segment.io/v1/b. The https://api.segment.io/v1/batch endpoint is reserved for events arriving from server side sending, and proxying to that endpoint for your mobile events may result in unexpected behavior.

Changelog

View the Analytics React Native changelog on GitHub.

This page was last modified: 30 Apr 2024



Get started with Segment

Segment is the easiest way to integrate your websites & mobile apps data to over 300 analytics and growth tools.
or
Create free account