React Native SDK
This is the official documentation for the Amplitude Analytics React Native SDK.
Compatibility matrix
The following matrix lists Amplitude React Native SDK version support across different versions of React Native and React Native CLI.
| @amplitude/react-native | react-native | Gradle | Android Gradle Plugin |
|---|---|---|---|
| >= 2.17.1 | >= 0.71 | 7.5.1+ | 7.2.1+ |
| <= 2.17.0 | >= 0.61, <= 0.70 | 3.5.3+ | 3.5.3+ |
Learn more about the Android Gradle plugin compatibility.
Install the SDK
Run yarn add @amplitude/react-native in your project directory, at the same level as package.json.
yarn add @amplitude/react-native
iOS installation
cd ios && pod install
Initialize the SDK
Before instrumenting, initialize the SDK using the API key for your Amplitude project.
import * as React from 'react';
import { Button } from 'react-native';
import { Amplitude, Identify } from '@amplitude/react-native';
const ampInstance = Amplitude.getInstance();
ampInstance.init(AMPLITUDE_API_KEY);
export function MyApp() {
return (
<Button
title="Log Event"
onPress=() => ampInstance.logEvent('BUTTON_CLICKED')
/>
);
}
Configure the SDK
Amplitude React Native SDK runs on top of the Amplitude Android Maintenance SDK and Amplitude iOS Maintenance SDK. The following ts/js config options are settable. For other default configurations:
- For Android, refer to the Android configuration.
- For iOS, refer to the iOS configuration.
| Name | Description | Default value |
|---|---|---|
enableCoppaControl() | Enable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking. For example, Amplitude.getInstance().enableCoppaControl();. | Coppa control is disabled by default. |
disableCoppaControl() | Disable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking. For example, Amplitude.getInstance().disableCoppaControl();. | Coppa control is disabled by default. |
setAdvertisingIdForDeviceId() | boolean. Use the Advertising ID on Android if available from Google Play Services. For example, Amplitude.getInstance().setAdvertisingIdForDeviceId();. Refer to the Android SDK docs for the required module and permission. | false |
setAppSetIdForDeviceId() | boolean. Use the App Set ID (fall back to this useAdvertisingIdForDeviceId is used) for device ID. For example, Amplitude.getInstance().setAppSetIdForDeviceId();. Refer to the Android SDK docs for the required module and permission. | false |
setOptOut() | boolean. Enables tracking opt-out. If the user wants to opt out of all tracking, use this method to enable opt-out for them. After opt-out is enabled, the SDK doesn't save events locally or send them to the server. For example, Amplitude.getInstance().setOptOut(true);. | false |
trackingSessionEvents() | boolean. Whether to automatically log start and end session events corresponding to the start and end of a user's session. For example, Amplitude.getInstance().trackingSessionEvents(true);. | false |
setUseDynamicConfig() | boolean. Whether to dynamically adjust the server URL. For example, Amplitude.getInstance().setUseDynamicConfig(true);. | false |
setMinTimeBetweenSessionsMillis() | number. Sets the minimum cutoff time in milliseconds for sessions to be considered distinct. For example, Amplitude.getInstance().setMinTimeBetweenSessionsMillis(600000);. The input parameter is in milliseconds. | 5 minutes. 30 minutes if foreground checking isn't enabled on Android. |
setServerZone() | serverZone: string, updateServerUrl:boolean. serverZone: US or EU. updateServerUrl: whether to enable dynamic configuration. Sets the Amplitude server zone, switching to zone-related configuration, including dynamic configuration. If updateServerUrl is true, the SDK also updates the server URL. For example, Amplitude.getInstance().setServerZone('EU', true);. | The serverZone is US, and dynamic configuration is enabled by default. |
setServerUrl() | string. Sets the API endpoint URL where the SDK sends events. ServerZone selects this automatically. For example, Amplitude.getInstance().setServerUrl("https://www.your-server-url.com"). | https://api2.amplitude.com/ |
setEventUploadMaxBatchSize() | number. Sets event upload max batch size. This controls the maximum number of events sent with each upload request. For example, Amplitude.getInstance().setEventUploadMaxBatchSize(100);. | 50 on Android. 100 on iOS. |
setEventUploadPeriodMillis() | number. Sets event upload period millis. The SDK attempts to batch upload unsent events every eventUploadPeriodMillis milliseconds, or when the unsent event count exceeds the event upload threshold. The input parameter is in milliseconds. For example, Amplitude.getInstance().setEventUploadPeriodMillis(100000);. | 30 Seconds |
setEventUploadThreshold() | number. Sets event upload threshold. The SDK attempts to batch upload unsent events every eventUploadPeriodMillis milliseconds, or when the unsent event count exceeds the event upload threshold. For example, Amplitude.getInstance().setEventUploadThreshold(100);. | 30 |
enableLogging() | boolean. Only for Android. Whether to enable message logging by the SDK. For example, Amplitude.getInstance().enableLogging(false);. | true |
setLogLevel() | number. 2 - Log.VERBOSE or 3 - Log.DEBUG or 4 - Log.INFO or 5 - Log.WARN or 6 - Log.ERROR or 7 - Log.ASSERT. Only for Android. Sets the logging level. Logging messages only appear when their severity matches or exceeds the set log level. | Log.INFO |
addLogCallback() | (error: AmplitudeLogError) => void. Only for Android. Adds a log callback to help read and collect error messages from the SDK. The callback function uses the following format: ({ tag, message }: { tag: string, message: string }) => { //implement your own logic} | null |
Configure batching behavior
To support high-performance environments, the SDK sends events in batches. The logEvent method queues every event in memory. The SDK flushes events in batches in the background. Customize batch behavior with setEventUploadThreshold and setEventUploadPeriodMillis. By default, the serverUrl is https://api2.amplitude.com/. This SDK doesn't support batch mode through the batch API endpoint.
// Events queued in memory will flush when number of events exceed upload threshold
// Default value is 30
Amplitude.getInstance().setEventUploadThreshold(100);
// Events queue will flush every certain milliseconds based on setting
// Default value is 30 second.
Amplitude.getInstance().setEventUploadPeriodMillis(100000);
EU data residency
Starting with version 2.6.0, configure the server zone after initializing the client to send data to Amplitude's EU servers. The SDK sends data based on the server zone when set. The server zone configuration also supports dynamic configuration.
For earlier versions, configure the serverURL property after initializing the client.
For EU data residency, set up the project inside Amplitude EU. Initialize the SDK with the API key from Amplitude EU.
// For versions starting from 2.6.0
// No need to call setServerUrl for sending data to Amplitude's EU servers
Amplitude.getInstance().setServerZone('EU');
// For earlier versions
Amplitude.getInstance().setServerUrl("https://api.eu.amplitude.com"));
Send basic events
Events represent how users interact with your application. For example, "button clicked" might be an action you want to track.
Amplitude.getInstance().logEvent("BUTTON_CLICKED");
Send events with properties
Events can also contain properties that give context about the event. For example, "hover time" might be a relevant event property for "button click".
Amplitude.getInstance().logEvent("BUTTON_CLICKED", { "Hover Time": "100ms" });
Flush events
The SDK typically stores events in a buffer and flushes them periodically. This behavior is configurable. You can also flush events manually.
Amplitude.getInstance().uploadEvents();
User properties
User properties help you understand your users at the time they perform an action within your app, such as their device details, their preferences, or language.
Amplitude-ReactNative's Identify class manages these features. Import Identify before using it.
import { Identify } from "@amplitude/react-native";
Set a user property
set sets the value of a user property. You can also chain together multiple identify calls.
const identify = new Identify();
identify.set("gender", "female").set("age", 20);
Amplitude.getInstance().identify(identify);
setOnce
setOnce sets the value of a user property once. Later calls using setOnce are ignored.
const identify1 = new Identify();
identify1.setOnce("sign_up_date", "2015-08-24");
Amplitude.getInstance().identify(identify1);
const identify2 = new Identify();
identify2.setOnce("sign_up_date", "2015-08-24");
Amplitude.getInstance().identify(identify2); // is ignored
add
add increments a user property by a numerical value. If the user property doesn't have a value set yet, the SDK initializes it to 0 before incrementing.
const identify = new Identify();
identify.add("karma", 0.123);
Amplitude.getInstance().identify(identify);
Set multiple user properties
Use setUserProperties as a shorthand to set multiple user properties at once. This method is a wrapper around Identify.set and identify.
const userProperties = {
KEY: "VALUE",
OTHER_KEY: "OTHER_VALUE",
};
Amplitude.getInstance().setUserProperties(userProperties);
Arrays in user properties
You can use arrays as user properties. Set arrays directly, or use append to generate an array.
const colors = ["rose", "gold"];
const numbers = [4, 5];
const identify = new Identify();
identify
.set("colors", colors)
.append("ab-tests", "campaign_a")
.append("existing_list", numbers);
Amplitude.getInstance().identify(identify);
append
append appends a value or values to a user property array. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before adding the new values. If the user property has an existing non-list value, the SDK converts it into a list and adds the new value.
const array = ["some_string", 56];
const identify = new Identify();
identify.append("ab-tests", "new-user-test");
Amplitude.getInstance().identify(identify);
preInsert
preInsert inserts a value or values to a user property if the value doesn't already exist in the user property. Pre-insert means inserting the value at the beginning of a given list. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before pre-inserting the new values. If the user property has an existing value, this is a no-op.
const array = ["some_string", 56];
const identify = new Identify();
identify.preInsert("ab-tests", "new-user-test");
Amplitude.getInstance().identify(identify);
postInsert
postInsert inserts a value or values to a user property if the value doesn't already exist in the user property. Post-insert means inserting the value at the end of a given list. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before post-inserting the new values. If the user property has an existing value, this is a no-op.
const array = ["some_string", 56];
const identify = new Identify();
identify.postInsert("ab-tests", "new-user-test");
Amplitude.getInstance().identify(identify);
Remove user properties
clearUserProperties wipes all the current user's user properties.
This is a permanent action
This action clears all user properties. Amplitude can't sync the user's user property values from before the wipe to any of the user's future events.
Amplitude.getInstance().clearUserProperties();
remove
remove removes a value or values from a user property when the value exists in the user property. If the item doesn't exist in the user property, nothing happens.
const array = ["some_string", 56];
const identify = new Identify();
identify.remove("ab-tests", "new-user-test").remove("some_list", array);
Amplitude.getInstance().identify(identify);
unset
unset unsets and removes a user property.
const identify = new Identify();
identify.unset("karma").unset("gender");
Amplitude.getInstance().identify(identify);
Track revenue
Amplitude can track revenue generated by a user. Amplitude tracks revenue through distinct revenue objects, which have special fields that Amplitude's Event Segmentation and Revenue LTV charts use.
This lets Amplitude automatically display revenue-related data in the platform. Revenue objects support the following special properties, as well as user-defined properties through the eventProperties field.
Price can be a negative value, which is useful for tracking lost revenue.
Amplitude doesn't support currency conversion. Normalize all revenue data to your currency of choice before sending.
type RevenueProperties = {
price: number;
productId?: string;
quantity?: number;
revenueType?: string;
receipt?: string;
receiptSignature?: string;
eventProperties?: PropertiesObject;
};
const userProperties = {
price: 100;
productId: "123";
quantity: 2;
revenueType: "productRevenue";
receipt: "11111";
receiptSignature: "signature";
eventProperties: {
"KAY": "VALUE",
"OTHER_KEY": "OTHER_VALUE"
};
}
Amplitude.getInstance().logRevenue(userProperties);
Group user properties
Use the Group Identify API to set or update the properties of particular groups. Keep these considerations in mind:
- Updates affect only future events, and don't update historical events.
- You can track up to 5 unique group types and 10 total groups.
The groupIdentify method accepts a group type string parameter, a group name object parameter, and an Identify object to apply to the group.
const identify = new Identify();
identify.set("gender", "female").set("age", 20);
Amplitude.getInstance().groupIdentify("groupType", "groupValue", identify);
User sessions
A session is a period of time when a user has the app in the foreground. Events logged within the same session have the same session_id.
The SDK handles sessions automatically, so you don't have to manually call an API like startSession() or endSession(). Amplitude groups events together by session.
A session represents a single period of user activity, with a start and end time. Different SDKs track sessions differently, depending on platform requirements.
You can determine whether to automatically log start and end session events corresponding to the start and end of a user's session.
//Enable automatically log start and end session events
Amplitude.getInstance().trackingSessionEvents(true);
//Disable automatically log start and end session events
Amplitude.getInstance().trackingSessionEvents(false);
Set a custom user ID
If your app has its own login system that you want to track users with, call setUserId at any time.
Amplitude.getInstance().setUserId("test_user_id");
Advanced topics
COPPA control
You can enable or disable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address, and location tracking all at once.
Remember that apps asking for information from children under 13 years of age must comply with COPPA.
// Enable COPPA Control
Amplitude.instance().enableCoppaControl();
// Disable COPPA Control
Amplitude.instance().disableCoppaControl();
Opt users out of tracking
Users might want to opt out of tracking entirely, which means no events and no records of their browsing history. setOptOut provides a way to fulfill certain users' requests for privacy.
//Disables instrumentation
Amplitude.getInstance().setOptOut(true);
//Enables instrumentation
Amplitude.getInstance().setOptOut(false);
Dynamic configuration
The React Native SDK lets users configure their apps to use dynamic configuration. This feature finds the best server URL automatically based on app users' location.
- If you have your own proxy server and use
setServerUrlAPI, don't use dynamic configuration. - If you have users in Mainland China, Amplitude recommends that you use dynamic configuration.
- By default, this feature is off. You must explicitly enable it to use it.
- By default, this feature returns the server URL of Amplitude's US servers. If you need to send data to Amplitude's EU servers, use
setServerZoneto set it to EU zone.
Amplitude.getInstance().setUseDynamicConfig(true);
Troubleshooting
Using an older React Native version and having trouble with iOS?
Amplitude supports versions of React Native >= 0.61. Here's the process to set up with React Native 0.71. Refer to the compatibility matrix for more details.
- Swift setup (Xcode).
- Open your
[project-name].xcodeprojfile in Xcode. - Right-click your project name in the file navigator, then select New File and pick Swift. Xcode prompts you to create a bridging headers file. This is necessary to support Swift in RN 0.61.
- Source of this fix: https://stackoverflow.com/a/54586937.
- Open your
- Podfile changes.
- Make sure you target iOS 10 or greater.
- Add
use_modular_headers!globally to the top of the Podfile. - Disable modular headers for DoubleConversion, Glog and Folly using
:use_modular_headers => false.
Was this helpful?