• SDKS
No results for ""


React Native SDK reference

Read time: 6 minutes
Last edited: Apr 07, 2021
SDK version compatibility

The latest version of the SDK is compatible with Xcode 12 and React Native 0.63. If you need support for earlier versions of React Native, refer to older versions of the SDK.

This reference guide documents all of the methods available in our React Native SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, read React Native SDK GitHub repository. The online API docs contain the programmatic definitions of every type and method. Additionally you can clone and run a sample application using this SDK.

To learn more about the specific configuration options that are available in this SDK, read the SDK's API docs.

Getting Started

Expo usage

The LaunchDarkly React Native Client SDK does not work with Expo because the SDK uses native modules. Please consider using ExpoKit.

Building on top of our Getting Started guide, the following steps will get you started with using the LaunchDarkly SDK in your React Native code.

The first step is to install the LaunchDarkly SDK as a dependency. Add the LaunchDarkly npm dependency to your project and link it to your React Native project.

1npm install --save launchdarkly-react-native-client-sdk
2cd ios/
3pod install

You must have a Podfile in your ios/ directory. After you write the Podfile, run pod install in the ios/ directory. This SDK requires Xcode 12 and compiles against Swift 5.

use_frameworks! and undefined symbols errors
As of v2.1.0 use_frameworks! is not necessary in the Podfile. If you encounter an undefined symbols error when building without use_frameworks! in your Podfile you will need to create a new empty Swift file and accept the prompt to create a matching Objective-C bridging header. If you are building for multiple platforms, add those as targets for the bridging header. If you're still having trouble resolving the undefined symbols error, clean and rebuild and try again.
1platform :ios, '10.0'
2require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
4target 'YOUR_MODULE_NAME' do
5 # Pods for ReactNativeRestwrapper
6 pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
7 pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
8 pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
9 pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
10 pod 'React', :path => '../node_modules/react-native'
11 pod 'React-Core', :path => '../node_modules/react-native'
12 pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
13 pod 'React-Core/DevSupport', :path => '../node_modules/react-native'
14 pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
15 pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
16 pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
17 pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
18 pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
19 pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
20 pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
21 pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
22 pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
23 pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native'
25 pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
26 pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
27 pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
28 pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
29 pod 'React-callinvoker', :path => "../node_modules/react-native/ReactCommon/callinvoker"
30 pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
31 pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
33 pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
34 pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
35 pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
37 #launchdarkly-react-native-client-sdk dependencies
38 pod 'LaunchDarkly', '5.4.1'
40 use_native_modules!

Once the SDK is downloaded and saved in package.json and the other install steps are complete, you'll need to import it into your project:

1import LDClient from 'launchdarkly-react-native-client-sdk';

Once the SDK is installed and imported, you'll want to create a single, shared instance of LDClient, passing in the client and user configuration objects. To create a client instance, you need your environment's mobile key (available on your account settings page). Mobile keys are not secret. You can expose them in your client-side code with no risk.

1let client = new LDClient();
2let config = { "mobileKey": "YOUR_MOBILE_KEY" };
3let user = { "key": "user_key" };
5await client.configure(config, user);

Lastly, when your application is about to terminate, shut down LDClient. This ensures that the client releases any resources it is using, and that any pending analytics events are delivered to LaunchDarkly. If your application quits without this shutdown step, you may not see your requests and users on the dashboard, because they are derived from analytics events. This is something you only need to do once.

Mobile keys

Be sure to use a mobile key from your Environments page.

Never embed a server-side SDK key into a mobile application.

Client Configuration Options

You can also pass custom parameters to the client by creating a custom configuration object:

1let config =
2 { "mobileKey": "YOUR_MOBILE_KEY",
3 "connectionTimeoutMillis": 3000
4 };
5await client.configure(config, user);

The config object can include a variety of options. mobileKey is a required property, but all other properties are optional. To learn more about the specific configuration options that are available in this SDK, read the SDK's API docs.

User Configuration Options

Here is a complete user configuration object utilizing all available fields:

1let user =
2 { key: '2fbfa269b78e24c8e967f482b89c939b',
3 name: 'grace_hopper',
4 firstName: 'Grace',
5 lastName: 'Hopper',
6 email: 'gracehopper@example.net',
7 anonymous: false,
8 privateAttributeNames: ['name'],
9 country: 'USA',
10 avatar: 'avatar',
11 ip: '',
12 custom: {'groups': 'users'}
13 };

Let's walk through this code. The first key in the object is the user's key. In this case we've used the value 2fbfa269b78e24c8e967f482b89c939b. The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use any value such as a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

All of the other keys (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on the LaunchDarkly application dashboard, meaning that you can start segmenting and targeting users with these attributes.

In addition to built-in attributes like names and e-mail addresses, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above. Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us, including organizations, groups, andaccount plans. Anything you pass to us becomes available instantly on your dashboard.

Private attributes allow you to specify keys you do not want to be sent to the LaunchDarkly servers. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly. When this user is sent back to LaunchDarkly, the name attribute will be removed.

The anonymous key allows you to distinguish logged out or unregistered users while still using LaunchDarkly. Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. This keeps anonymous users from polluting your Users page.

You can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. If you use the same user key for every anonymous user, you also can't use percentage rollouts or Experimentation with anonymous users.

We recommend using the same user key for every initialization and then replacing that with the actual user key when you know who the user is. This way LaunchDarkly counts the initialization user key only once against your MAU, instead of every time you initialize.


The variation method determines whether a flag is enabled or not for a specific user. In React Native, there is a variation method for each type (e.g. boolVariation, stringVariation):

1let jsonResult = await client.jsonVariation('MY_JSON_FLAG_KEY', {});

Variation calls take the feature flag key and a default value.

The default value only returns if an error is encountered. For example, the default value returns if the feature flag key doesn't exist or the user doesn't have a key specified.

The variation call will automatically create a user in LaunchDarkly if a user with that user key doesn't exist already. There's no need to create users ahead of their initial use, but if you choose to do so, you can use the identify method to do so.

Handling flag values on initial application launch
When `LDClient` initializes for the first time at app launch, users receive feature flag default values until a connection to LaunchDarkly completes for the first time. Read the section above for various ways to initialize the client.
Making feature flags available to this SDK
You must make feature flags available to client-side SDKs before the flags can be evaluated. If you evaluate a feature flag that is not available, you will receive the default value for that flag. If you want a project's flags to be made available to this SDK by default, check the **SDKs using Mobile Key** checkbox in your project [Settings](https://app.launchdarkly.com/settings#/projects).


Since v2.1.0

The variationDetail methods work the same as variation, but also provide additional reason information about how a flag value was calculated (for instance, if the user matched a specific rule). You can examine the reason data programmatically; you can also view it with Data Export, if you are capturing detailed analytics events for this flag.

For more information, see Evaluation reasons.

All Flags

Creating users

Unlike variation and identify calls, allFlags does not send events to LaunchDarkly. When you use allFlags, users are not created or updated in the LaunchDarkly dashboard.

The allFlags method returns an object containing flag keys and values. You may also register a listener that will fire when any flag in your environment changes.

1let allFlagsResult = client.allFlags();
2allFlagsResult.then(values => {
3 console.log(values);
6// All Flags Listener
7let listenerId = "ARBITRARY_VALUE"
8let listener = value => Alert.alert('All Flags Listener Callback', value);
9client.registerAllFlagsListener(listenerId, listener);


The track method allows you to record actions your users take in your app. In the LaunchDarkly dashboard, you can tie these events to goals in A/B tests. You can also attach custom JSON data to your event by passing an extra parameter to track. Here's a simple example:

Since v2.1.0

You can now optionally add a metricValue parameter to the track method if you are using the latest version of Experimentation.

1client.track('MY_GOAL_FLAG_KEY', false);
2client.track('MY_GOAL_FLAG_KEY_WITH_DATA', {'some_data':'value'});

Offline Mode

In some situations, you might want to stop making remote calls to LaunchDarkly and switch to the last known values for your feature flags. Offline mode lets you do this easily.

1let offlineResult = client.setOffline(); //true or false
2let offlineStatus = client.isOffline(); //true or false
3let onlineResult = client.setOnline(); //true or false
Lack of network connectivity

If a user's device is not connected to a network, such as when the device is in airplane mode, the SDK uses the latest stored flag settings in memory. If there are no previously stored flag settings, the SDK uses the default values.


Internally, the LaunchDarkly SDK keeps an event buffer for track calls. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a simulator), you may want to manually call flush to process events immediately.



If your app is used by multiple users on a single device, you may want to change users and have separate flag settings for each user. To achieve this, the SDK will store the last 5 user contexts on a single device, with support for switching between different user contexts.

You can use the identify method to switch user contexts:

1let user = {'key': 'minimal_user'};
2await client.identify(user); //promise resolves to nil/null
3Alert.alert('identify', 'success');

The identify call will load any saved flag values for the new user and immediately trigger an update of the latest flags from LaunchDarkly.

Real-time Updates

LaunchDarkly manages all flags for a user context in real-time by updating flags based on a real-time event stream. When a flag is modified from the LaunchDarkly dashboard, the flag values for the current user will update almost immediately.

To accomplish real-time updates, LaunchDarkly broadcasts an event stream that is listened to by the React Native SDK. Whenever an event is performed on the dashboard, the React Native SDK is notified of the updated flag settings in real-time.

To perform real-time updates in your app, your app will need to register listeners for each flag you'd like to watch:

1if (this.state.listeners.hasOwnProperty(key)) {
2 return;
4let listener = value => Alert.alert('Listener Callback', value);
5client.registerFeatureFlagListener('MY_LISTEN_FLAG_KEY', listener);
6this.setState({listeners: {...this.state.listeners, ...{['MY_LISTEN_FLAG_KEY']: listener}}});

Similarly you can unregister listeners to disable them:

1this.state.ldClient.unregisterFeatureFlagListener('MY_LISTEN_FLAG_KEY', this.state.listeners['MY_LISTEN_FLAG_KEY']);
2let {['MY_LISTEN_FLAG_KEY']: omit, ...newListeners} = this.state.listeners;
3this.setState({listeners: newListeners});

Background Fetch

The React Native SDK defaults to the background fetch behavior for the platform it's running on.

Monitoring SDK Status

The React Native SDK exposes some of its internal status through the Connection Status API to allow your application to monitor the SDK's status. This is provided primarily as a mechanism for the application to determine how recently the internal flag cache has been updated with the most recent values, as well as diagnosing potential reasons for the flag cache to be out of date.

1const connectionMode = await client.getConnectionMode();
2const lastSuccessfulConnection = await client.getLastSuccessfulConnection();
3const lastFailedConnection = await client.getLastFailedConnection();
4const lastFailureReason = await client.getLastFailure();

To learn more about the return types, read the API documentation about LDConnectionMode and LDFailureReason.

Data collection

To learn more about data collection within this SDK and implications on submissions to the Apple App Store, read Apple App Store data collection policy.