Analytics for React Native
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 lets you 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.
Warning
@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.
To get started with the Analytics for React Native library:
-
Create a React Native Source in Segment.
- Go to Connections > Sources > Add source.
- Search for "React Native" and click Add Source.
-
Install
@segment/analytics-react-native,@segment/sovran-react-nativeandreact-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-valuesor
npm install --save @segment/analytics-react-native @segment/sovran-react-native react-native-get-random-values -
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-storageor
npm install --save @react-native-async-storage/async-storageTo 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, or you might get unexpected side effects like multiple 'Application Installed' events.
-
If you're using iOS, install native modules with:
npx pod-install -
If you're using Android, you need to add extra permissions to your
AndroidManifest.xml.<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> -
Initialize and configure the Analytics React Native client. The package exposes a method called
createClientwhich you can use to create the Segment Analytics client. This central client manages all the tracking events.1import { createClient, AnalyticsProvider } from '@segment/analytics-react-native';23const segmentClient = createClient({4writeKey: 'SEGMENT_API_KEY'5});
These are the options you can apply to configure the client:
| Name | Default | Description |
|---|---|---|
| writeKey | '' | Your Segment API key (required). |
| 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. |
| 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. |
| useSegmentEndpoints | false | Set to true to automatically append the Segment endpoints when using proxy or cdnProxy to send or fetch settings. Otherwise, proxy or cdnProxy will be used as is. |
You can add a plugin at any time using segmentClient.add(). More information about plugins, including a detailed architecture overview and a guide to creating your own, can be found in the Analytics React Native Plugin Architecture docs.
1import { createClient } from '@segment/analytics-react-native';23import { AmplitudeSessionPlugin } from '@segment/analytics-react-native-plugin-amplitude-session';4import { FirebasePlugin } from '@segment/analytics-react-native-plugin-firebase';5import { IdfaPlugin } from '@segment/analytics-react-native-plugin-idfa';67const segmentClient = createClient({8writeKey: 'SEGMENT_KEY'9});1011segmentClient.add({ plugin: new AmplitudeSessionPlugin() });12segmentClient.add({ plugin: new FirebasePlugin() });13segmentClient.add({ plugin: new IdfaPlugin() });
You can use Analytics React Native with or without 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.
1import {2createClient,3AnalyticsProvider,4} from '@segment/analytics-react-native';56const segmentClient = createClient({7writeKey: 'SEGMENT_API_KEY'8});910const App = () => (11<AnalyticsProvider client={segmentClient}>12<Content />13</AnalyticsProvider>14);
The useAnalytics() hook exposes the client methods:
1import React from 'react';2import { Text, TouchableOpacity } from 'react-native';3import { useAnalytics } from '@segment/analytics-react-native';45const Button = () => {6const { track } = useAnalytics();7return (8<TouchableOpacity9style={styles.button}10onPress={() => {11track('Awesome event');12}}13>14<Text style={styles.text}>Press me!</Text>15</TouchableOpacity>16);17};
To use the tracking events without hooks, call the methods directly on the client:
1import {2createClient,3AnalyticsProvider,4} from '@segment/analytics-react-native';56// create the client once when the app loads7const segmentClient = createClient({8writeKey: 'SEGMENT_API_KEY'9});1011// track an event using the client instance12segmentClient.track('Awesome event');
track: (event: string, properties?: JsonMap) => void;
Once you've installed the Analytics React Native library, you can start collecting data through Segment's tracking methods:
Destinations are the business tools or apps that Segment sends your data to. Adding destinations allows you to act on your data and learn more about your customers in real time.
Segment offers support for two different types of destination connection modes: cloud-mode and device-mode. Learn more about the differences between the two in the Segment destination docs.
group: (groupId: string, groupTraits?: JsonMap) => void;
The Analytics React Native 2.0 utility methods help you to manage your data. They include:
- Alias
- Reset
- Flush
- Cleanup
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;
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.
Warning
Each time you call Reset, Segment generates a new AnonymousId.
reset: () => void;
Info
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.
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>;
If 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.
1let client = createClient({2writeKey: 'KEY'3});45client.cleanup();67client = createClient({8writeKey: 'KEY'9});
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.
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:
1const client = createClient({2// ...3flushPolicies: [4new CountFlushPolicy(5),5new TimerFlushPolicy(500),6new StartupFlushPolicy(),7],8});
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 triggers 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:
CountFlushPolicytriggers when you reach a certain number of eventsTimerFlushPolicytriggers on an interval of millisecondsStartupFlushPolicytriggers on client startup only
Info
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.
Flush policies can be added and removed while the application runs, which lets you adjust the number of flushes as needed.
For example, to disable flushes if you detect the user has no network:
1import NetInfo from "@react-native-community/netinfo";2const policiesIfNetworkIsUp = [3new CountFlushPolicy(5),4new TimerFlushPolicy(500),5];6// Create our client with our policies by default7const client = createClient({8// ...9flushPolicies: [...policiesIfNetworkIsUp],10});11// If Segment detects the user disconnect from the network, Segment removes all flush policies.12// That way the Segment client won't keep attempting to send events to Segment but will still13// store them for future upload.14// If the network comes back up, the Segment client adds the policies back.15const unsubscribe = NetInfo.addEventListener((state) => {16if (state.isConnected) {17client.addFlushPolicy(...policiesIfNetworkIsUp);18} else {19client.removeFlushPolicy(...policiesIfNetworkIsUp)20}21});
You can create a custom flush policy by implementing the FlushPolicy interface. You can also extend the FlushPolicyBase class which already creates and handles the shouldFlush value reset.
A FlushPolicy must implement two of the following methods:
start(): Runs when the flush policy is enabled and added to the client. Use this method to start background operations, make asynchronous calls, or configure settings before execution.onEvent(event: SegmentEvent): Runs on every event tracked by your client.reset(): Runs after a flush is triggered by your policy, 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 based on its logic, although it's common to do this in the reset method.
1export class FlushOnScreenEventsPolicy extends FlushPolicyBase {2onEvent(event: SegmentEvent): void {3// Only flush when a screen even happens4if (event.type \5EventType.ScreenEvent) {6this.shouldFlush.value = true;7}8}9reset(): void {10// Superclass will reset the shouldFlush value so that the next screen event triggers a flush again.11// But you can also reset the value whenever, say another event comes in or after a timeout12super.reset();13}14}
To avoid sending a Screen event with each navigation action, you can track navigation globally. The implementation depends on which navigation library you use. The two main navigation libraries for React Native are React Navigation and React Native Navigation.
Segment's plugin architecture lets you modify and augment how the events are processed before they're uploaded to the Segment API. 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 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 like Logging. |
Info
Plugins can have their own native code (like the iOS-only IdfaPlugin) or wrap an underlying library (like the FirebasePlugin which uses react-native-firebase under the hood).
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, set autoAddSegmentDestination = false in the options when setting up your client. This prevents the SegmentDestination plugin from being added automatically.
You can add a plugin at any time using segmentClient.add().
12import { createClient } from '@segment/analytics-react-native';34import { AmplitudeSessionPlugin } from '@segment/analytics-react-native-plugin-amplitude';5import { FirebasePlugin } from '@segment/analytics-react-native-plugin-firebase';6import { IdfaPlugin } from '@segment/analytics-react-native-plugin-idfa';78const segmentClient = createClient({9writeKey: 'SEGMENT_KEY'10});1112segmentClient.add({ plugin: new AmplitudeSessionPlugin() });13segmentClient.add({ plugin: new FirebasePlugin() });14segmentClient.add({ plugin: new IdfaPlugin() });
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:
PluginEventPluginDestinationPluginUtilityPluginPlatformPlugin
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:
1// logger.js23import {4Plugin,5PluginType,6SegmentEvent,7} from '@segment/analytics-react-native';89export class Logger extends Plugin {1011// Note that `type` is set as a class property.12// If you do not set a type your plugin will be a `utility` plugin (see Plugin Types above)13type = PluginType.before;1415execute(event: SegmentEvent) {16console.log(event);17return event;18}19}20// app.js2122import { Logger } from './logger';2324segmentClient.add({ plugin: new Logger() });
As the plugin overrides execute(), this Logger calls console.log for every event going through the timeline.
You can add custom plugins to destination plugins. For example, you could implement the following logic to send events to Braze on weekends only:
12import { createClient } from '@segment/analytics-react-native';34import {BrazePlugin} from '@segment/analytics-react-native-plugin-braze';5import {BrazeEventPlugin} from './BrazeEventPlugin';67const segmentClient = createClient({8writeKey: 'SEGMENT_KEY'9});1011const brazeplugin = new BrazePlugin();12const myBrazeEventPlugin = new BrazeEventPlugin();13brazeplugin.add(myBrazeEventPlugin);14segmentClient.add({plugin: brazeplugin});1516// Plugin code for BrazeEventPlugin.ts17import {18Plugin,19PluginType,20SegmentEvent,21} from '@segment/analytics-react-native';2223export class BrazeEventPlugin extends Plugin {24type = PluginType.before;2526execute(event: SegmentEvent) {27var today = new Date();28if (today.getDay() === 6 || today.getDay() === 0) {29return event;30}31}32}
Segment would then send events to the Braze pestination plugin on Saturdays and Sundays, based on device time.
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 |
Destination filters are only available to Business Tier customers
Destination filters on mobile device-mode destinations are in beta and only support Analytics-React-Native 2.0, Analytics-Swift and Analytics-Kotlin.
Use Analytics-React-Native 2.0 to set up destination filters on your mobile device-mode destinations.
You must use Analytics-React-Native version 2.9 or higher to implement destination filters
Keep these limitations in mind when using destination filters.
To get started with destination filters on mobile device-mode destinations using Analytics-React-Native 2.0:
-
Download and install the
@segment/analytics-react-native-plugin-destination-filterspackage as a dependency in your project.- Using NPM:
npm install --save @segment/analytics-react-native-plugin-destination-filters
- Using Yarn:
yarn add @segment/analytics-react-native-plugin-destination-filters
- Using NPM:
-
Follow the instructions for adding plugins on the main Analytics client.
-
Add
DestinationFiltersPluginafter you create your Segment client.1import { createClient } from '@segment/analytics-react-native';23import { DestinationFiltersPlugin } from '@segment/analytics-react-native-plugin-destination-filters';45const segmentClient = createClient({6writeKey: 'SEGMENT_KEY'7});89segmentClient.add({ plugin: new DestinationFiltersPlugin() });10segment.add({ plugin: new FirebasePlugin() })
Segment supports a large number of cloud-mode destinations. Segment also supports the following destinations for Analytics React Native 2.0 in device-mode:
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 to 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.
Find answers to common Analytics React Native questions.
No, only the plugins listed are supported in device-mode for Analytics React Native 2.0.
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.
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.
You can set different writeKeys for iOS and Android. This is useful 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:
1import {Platform} from 'react-native';2import { createClient } from '@segment/analytics-react-native';34const segmentWriteKey = Platform.iOS ? 'ios-writekey' : 'android-writekey';56const segmentClient = createClient({7writeKey: segmentWriteKey8});
The instanceId was introduced in v2.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.
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:
1import {2EventType,3Plugin,4PluginType,5SegmentEvent,6} from '@segment/analytics-react-native';78export class Modify extends Plugin {9type = PluginType.before;1011async execute(event: SegmentEvent) {12if (event.type == EventType.TrackEvent) {13let integrations = event.integrations;14if (integrations !== undefined) {15integrations['Appboy'] = false;16}17}18//console.log(event);19return event;20}21}
You need to use a plugin to access and modify the Context object. For example, to add context.groupId to every Track call, create a plugin like this:
1//in AddToContextPlugin.js2import {3Plugin,4PluginType,5SegmentEvent,6} from '@segment/analytics-react-native';78export class AddToContextPlugin extends Plugin {9// Note that `type` is set as a class property10// If you do not set a type your plugin will be a `utility` plugin (see Plugin Types above)11type = PluginType.enrichment;1213async execute(event: SegmentEvent) {14if (event.type == EventType.TrackEvent) {15event.context['groupId'] = 'test - 6/8'16}17return event;18}19}20// in App.js2122import { AddToContextPlugin } from './AddToContextPlugin'2324segmentClient.add({ plugin: new AddToContextPlugin() });
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, Segment recommends updating those tracks to resolve the issue.
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 using a blockList.
The Reset 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.
1segmentClient.userInfo.set((currentUserInfo) => {2return {3...currentUserInfo,4traits: {5// All the traits except the one you want to delete6persistentTrait: currentUserInfo.persistentTrait7}8});
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. Proxying to that endpoint for your mobile events may result in unexpected behavior.
View the Analytics React Native changelog on GitHub.