Experiment React Native SDK (Legacy)
The legacy SDK receives only bug fixes until deprecation. 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.
npm install --save @amplitude/experiment-react-native-client
Quick start
// (1) Initialize the experiment client
await Experiment.initialize('<DEPLOYMENT_KEY>');
// (2) Fetch variants for a user
const user = {
user_id: 'user@company.com',
device_id: 'abcdefg',
user_properties: {
'premium': true,
},
};
await Experiment.fetch(user);
// (3) Lookup a flag's variant
const variant = await Experiment.variant('<FLAG_KEY>');
if (variant.value === 'on') {
// Flag is on
} else {
// Flag is off
}
Core functions
The following functions make up the core of the Experiment client-side SDK.
Async functions
Native SDKs run internally, so you need to await the result of all functions.
Initialize
Initialize the SDK client in your application on startup. The deployment key argument you pass to the apiKey parameter must live within the same project that you are sending analytics events to.
initialize(apiKey: string, config?: ExperimentConfig): Promise<boolean>
| Parameter | Requirement | Description |
|---|---|---|
apiKey | required | The deployment key that authorizes fetch requests and determines which flags to evaluate 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 always return the initial instance. To create multiple instances, use the instanceName configuration.
const 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 with the Amplitude Analytics SDK. Update your SDK versions to the latest, and use the special integration initialization function.
await Amplitude.getInstance().init('<API_KEY>');
await Experiment.initializeWithAmplitudeAnalytics('<DEPLOYMENT_KEY>');
If you are using a custom instance name for analytics, set the same value in the instanceName configuration option in the experiment SDK.
The integration initializer configures 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
Configure the SDK client during 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 doesn't exist. | {} |
initialVariants | An initial set of variants to access. This field helps bootstrap 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 to retry variant fetches in the background if the request doesn't succeed. | true |
automaticExposureTracking | If true, calling variant() tracks 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 integrate with the Amplitude Analytics SDK. If true any change to the user ID, device ID or user properties from analytics triggers the experiment SDK to fetch variants and update its cache. | false |
userProvider | An interface used to provide the user object to fetch() when called. | 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 stores the results in the client for fast access. The function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.
fetch(user?: ExperimentUser): Promise<boolean>
| Parameter | Requirement | Description |
|---|---|---|
user | optional | Explicit user information to pass with the request to evaluate. The SDK merges this user information with user information provided from integrations through 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 to avoid the interface "flickering".
const user = {
user_id: 'user@company.com',
device_id: 'abcdefg',
user_properties: {
'premium': true,
},
};
await Experiment.fetch(user);
If you're using an integration or a custom user provider then you can fetch without inputting the user.
await Experiment.fetch();
Fetch when user identity changes
If you want the most up-to-date variants for the user, 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 affect 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 before remote evaluation. Remote user-property sync through a separate system has no timing guarantees for fetch(), which can create a race condition.
Timeout and retries
If fetch() times out (default 10 seconds) or fails for any reason, the SDK client returns and retries in the background with back-off. You may configure the timeout or disable retries in the configuration options during SDK client initialization.
Variant
Access a variant for a flag or experiment from the SDK client's local store.
Automatic exposure tracking
When you use an integration or set a custom exposure tracking provider, variant() automatically tracks an exposure event through the tracking provider. To disable this functionality, configure automaticExposureTracking to be false, and track exposures manually using exposure().
variant(key: string): Promise<Variant>
variantWithFallback(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.
const variant = await Experiment.variant('<FLAG_KEY>');
if (variant.value === 'on') {
// Flag is on
} else {
// Flag is off
}
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.
const variant = await Experiment.variant('<FLAG_KEY>');
if (variant.value === 'on') {
const payload = variant.payload;
}
A null variant value means that the user hasn't been bucketed into a variant. You may use the built in fallback parameter to provide a variant to return if the store doesn't contain a variant for the given flag key.
const variant = await Experiment.variantWithFallback('<FLAG_KEY>', { value: 'control' });
if (variant === 'control') {
// Control
} else if (variant === 'treatment') {
// Treatment
}
All
Access all variants stored by the SDK client.
all(): 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.
exposure(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. |
const variant = await Experiment.variant('<FLAG_KEY>');
// Do other things...
await Experiment.exposure('<FLAG_KEY>');
if (variant === 'control') {
// Control
} else if (variant === 'treatment') {
// Treatment
}
Was this helpful?