Experiment React Native SDK (Legacy)

Warning

This SDK is legacy and will only continue to receive bug fixes until it is eventually deprecated. We recommend upgrading to v1.0.0+ which supports SDK integrations, React Native Web, Expo, and more.

Official documentation for Amplitude Experiment's Client-side React Native SDK.

Install

Web compatibility

Experiment React Native SDK is only compatible with iOS and Android React Native projects. Use the JavaScript SDK to support all three platforms.

Install the Experiment JavaScript Client SDK.

1npm install --save @amplitude/experiment-react-native-client

1yarn add @amplitude/experiment-react-native-client

Quick start

  1. Initialize the experiment client
  2. Fetch variants for the user
  3. Access a flag's variant
1// (1) Initialize the experiment client
2await Experiment.initialize('<DEPLOYMENT_KEY>');
3 
4// (2) Fetch variants for a user
5const user = {
6 user_id: 'user@company.com',
7 device_id: 'abcdefg',
8 user_properties: {
9 'premium': true,
10 },
11};
12await Experiment.fetch(user);
13 
14// (3) Lookup a flag's variant
15const variant = await Experiment.variant('<FLAG_KEY>');
16if (variant.value === 'on') {
17 // Flag is on
18} else {
19 // Flag is off
20}

Core functions

The following functions make up the core of the Experiment client-side SDK.

Async functions

Native SDKs are used under-the-hood, so you need to await the result of all functions.

Initialize

The SDK client should be initialized in your application on startup. The deployment key argument passed into the apiKey parameter must live within the same project that you are sending analytics events to.

1initialize(apiKey: string, config?: ExperimentConfig): Promise<boolean>
Parameter Requirement Description
apiKey required The deployment key which authorizes fetch requests and determines which flags should be evaluated for the user.
config optional The client configuration used to customize SDK client behavior.

The initializer returns a singleton instance, so subsequent initializations for the same instance name will always return the initial instance. To create multiple instances, use the instanceName configuration.

1const experiment = await Experiment.initialize('<DEPLOYMENT_KEY>');

Integrations

If you use either Amplitude or Segment Analytics SDKs to track events into Amplitude, you'll want to set up an integration on initialization. Integrations automatically implement provider interfaces to enable a more streamlined developer experience by making it easier to manage user identity and track exposures events.

Amplitude integration

The Amplitude Experiment SDK is set up to integrate seamlessly with the Amplitude Analytics SDK. All you need to do is update your SDK versions to the latest, and use the special integration initialization function.

1await Amplitude.getInstance().init('<API_KEY>');
2await Experiment.initializeWithAmplitudeAnalytics('<DEPLOYMENT_KEY>');

Note that, if you are using a custom instance name for analytics, you will need to set the same value in the instanceName configuration option in the experiment SDK.

Using the integration initializer will automatically configure implementations of the user provider and exposure tracking provider interfaces to pull user data from the Amplitude Analytics SDK and track exposure events.

Supported Versions

Analytics SDK Version Experiment SDK Version
2.8.0+ 0.6.0+

Configuration

The SDK client can be configured once on initialization.

Name
Description Default Value
debug Enable additional debug logging within the SDK. Should be set to false in production builds. false
fallbackVariant The default variant to fall back if a variant for the provided key does not exist. {}
initialVariants An initial set of variants to access. This field is valuable for bootstrapping the client SDK with values rendered by the server using server-side rendering (SSR). {}
serverUrl The host to fetch variants from. https://api.lab.amplitude.com
fetchTimeoutMillis The timeout for fetching variants in milliseconds. 10000
retryFetchOnFailure Whether or not to retry variant fetches in the background if the request does not succeed. true
automaticExposureTracking If true, calling variant() will track an exposure event through the configured exposureTrackingProvider. If no exposure tracking provider is set, this configuration option does nothing. true
automaticFetchOnAmplitudeIdentityChange Only matters if you use the initializeWithAmplitudeAnalytics initialization function to seamlessly integrate with the Amplitude Analytics SDK. If true any change to the user ID, device ID or user properties from analytics will trigger the experiment SDK to fetch variants and update it's cache. false
userProvider An interface used to provide the user object to fetch() when called. See Experiment User for more information. null
exposureTrackingProvider Implement and configure this interface to track exposure events through the experiment SDK, either automatically or explicitly. null
instanceName Custom instance name for experiment SDK instance. The value of this field is case-sensitive. null

EU data center

If you're using Amplitude's EU data center, configure the serverUrl option on initialization to https://api.lab.eu.amplitude.com

Fetch

Fetches variants for a user and store the results in the client for fast access. This function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.

1fetch(user?: ExperimentUser): Promise<boolean>
Parameter Requirement Description
user optional Explicit user information to pass with the request to evaluate. This user information is merged with user information provided from integrations via the user provider, preferring properties passed explicitly to fetch() over provided properties.

Amplitude recommends calling fetch() during application start up so that the user gets the most up-to-date variants for the application session. Furthermore, you'll need to wait for the fetch request to return a result before rendering the user experience in order to avoid the interface "flickering".

1const user = {
2 user_id: 'user@company.com',
3 device_id: 'abcdefg',
4 user_properties: {
5 'premium': true,
6 },
7};
8await Experiment.fetch(user);

If you're using an integration or a custom user provider then you can fetch without inputting the user.

1await Experiment.fetch();

Fetch when user identity changes

If you want the most up-to-date variants for the user, it is recommended that you call fetch() whenever the user state changes in a meaningful way. For example, if the user logs in and receives a user ID, or has a user property set which may effect flag or experiment targeting rules.

In the case of user properties, Amplitude recommends passing new user properties explicitly to fetch() instead of relying on user enrichment prior to remote evaluation. This is because user properties that are synced remotely through a separate system have no timing guarantees with respect to fetch()--i.e. a race.

Timeout and retries

If fetch() times out (default 10 seconds) or fails for any reason, the SDK client will return and retry in the background with back-off. You may configure the timeout or disable retries in the configuration options when the SDK client is initialized.

Variant

Access a variant for a flag or experiment from the SDK client's local store.

Automatic exposure tracking

When an integration is used or a custom exposure tracking provider is set, variant() will automatically track an exposure event through the tracking provider. To disable this functionality, configure automaticExposureTracking to be false, and track exposures manually using exposure().

1variant(key: string): Promise<Variant>
1variantWithFallback(key: string, fallback: Variant): Promise<Variant>
Parameter Requirement Description
key required The flag key to identify the flag or experiment to access the variant for.
fallback optional The value to return if no variant was found for the given flagKey.

When determining which variant a user has been bucketed into, you'll want to compare the variant value to a well-known string.

1const variant = await Experiment.variant('<FLAG_KEY>');
2if (variant.value === 'on') {
3 // Flag is on
4} else {
5 // Flag is off
6}

Access the variant's payload

A variant may also be configured with a dynamic payload of arbitrary data. Access the payload field from the variant object after checking the variant's value.

1const variant = await Experiment.variant('<FLAG_KEY>');
2if (variant.value === 'on') {
3 const payload = variant.payload;
4}

A null variant value means that the user has not been bucketed into a variant. You may use the built in fallback parameter to provide a variant to return if the store does not contain a variant for the given flag key.

1const variant = await Experiment.variantWithFallback('<FLAG_KEY>', { value: 'control' });
2if (variant === 'control') {
3 // Control
4} else if (variant === 'treatment') {
5 // Treatment
6}

All

Access all variants stored by the SDK client.

1all(): Promise<Variants>

Exposure

Manually track an exposure event for the current variant of the given flag key through configured integration or custom exposure tracking provider. Generally used in conjunction with setting the automaticExposureTracking configuration optional to false.

1exposure(key: string): Promise<boolean>
Parameter Requirement Description
key required The flag key to identify the flag or experiment variant to track an exposure event for.
1const variant = await Experiment.variant('<FLAG_KEY>');
2 
3// Do other things...
4 
5await Experiment.exposure('<FLAG_KEY>');
6if (variant === 'control') {
7 // Control
8} else if (variant === 'treatment') {
9 // Treatment
10}
Was this page helpful?

Thanks for your feedback!

June 4th, 2024

Need help? Contact Support

Visit Amplitude.com

Have a look at the Amplitude Blog

Learn more at Amplitude Academy

© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.