---
title: React Native SDK quickstart
slug: feature-experimentation/docs/react-native-sdk-quickstart
docTags: 
createdAt: 2026-08-05T20:39:52.000Z
---

:::hint{type="info"}
**Note**
This quickstart is for React Native SDK v4+. For versions 3.x and earlier, see the [React Native SDK prior to v4](docId\:GlBDkcbSF-aCoq3njjxtw).
:::

## Part 1: Create a sample app

### 1. Get a free account

You need an Optimizely account to follow this guide. If you do not have an account, you can [register for a free account](https://www.optimizely.com/free-feature-flagging/). If you already have an account, navigate to your Feature Experimentation project.

### 2. Get your SDK key

To find your SDK Key in your Optimizely project:

1. Go to **Settings** > **Primary Environment**.
2. Copy and save the **SDK Key** for your primary environment.

:::hint{type="warning"}
**Important**
Each environment has its own SDK key. Ensure you copy the correct key.
:::

![SDK key for primary environment](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/TEbXdmYlSZ9qVcA3GiXVm-20260723-144350.png "sdk_key.png")

### 3. Copy the sample code

To try out the SDK:

1. Create a new React Native app:

```shell
npx @react-native-community/cli init OptimizelyRNQuickstart
cd OptimizelyRNQuickstart
```

2. Install the Optimizely React SDK and required peer dependencies:

```shell
npm install @optimizely/react-sdk @react-native-async-storage/async-storage @react-native-community/netinfo react-native-get-random-values fast-text-encoding
```

The React SDK is open source and available on [GitHub](https://github.com/optimizely/react-sdk).

3. For iOS, install CocoaPods dependencies:

```shell
cd ios && pod install && cd ..
```

4. Copy the following code sample into your `App.tsx` (or `App.js`) file. Replace `YOUR_SDK_KEY` with the SDK key you found in a previous step.

```javascript
import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import {
  createInstance,
  createPollingProjectConfigManager,
  createBatchEventProcessor,
  OptimizelyProvider,
  useDecide,
} from '@optimizely/react-sdk';

const optimizelyClient = createInstance({
  projectConfigManager: createPollingProjectConfigManager({
    sdkKey: 'YOUR_SDK_KEY',
  }),
  eventProcessor: createBatchEventProcessor(),
});

function App() {
  const [userId] = useState(() =>
    (Math.floor(Math.random() * 999999) + 100000).toString()
  );

  return (
    <OptimizelyProvider
      client={optimizelyClient}
      user={{ id: userId }}
    >
      <View style={styles.container}>
        <Text style={styles.text}>Welcome to our Quickstart Guide!</Text>
        <Text style={styles.text}>Your user ID: {userId}</Text>
        <Decision />
      </View>
    </OptimizelyProvider>
  );
}

function Decision() {
  const { decision, isLoading, error } = useDecide('product_sort');

  if (isLoading) return <Text style={styles.text}>Loading decision...</Text>;
  if (error) return <Text style={styles.text}>Error: {error.message}</Text>;

  const variationKey = decision.variationKey;
  const sortMethod = decision.variables['sort_method'];

  return (
    <Text style={styles.text}>
      {`Flag ${
        decision.enabled ? 'on' : 'off'
      }. You saw flag variation: ${variationKey} and got products sorted by: ${sortMethod} config variable as part of flag rule: ${
        decision.ruleKey
      }`}
    </Text>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 16,
  },
  text: {
    fontFamily: 'monospace',
    fontSize: 14,
    marginBottom: 8,
  },
});

export default App;
```

:::hint{type="info"}
**Note**
Do not run your app yet, because you still need to configure the flag in the Optimizely app.
:::

## Part 2: Run your app

After completing [Part 1](docId\:uUfLuItu1iCv6iAYW8tHO), your app does nothing. You need to create a flag and a flag rule in the Optimizely app to enable the app.

### 1. Create the feature flag

A [flag](docId\:CFAu9P5PdLLMB8GsFn_fo) lets you control the users that are exposed to new code in your application. For this quickstart, imagine that you are rolling out a redesigned sorting feature for displaying products.

Create a flag in your Feature Experimentation project named **product\_sort** and give it a variable named **sort\_method**:

1. Select **Create New Flag...** from the **Flags** tab.
2. Enter *product\_sort* in the **Name** field.
3. Keep the auto-created **Key**, *product\_sort*, and click **Create Flag**. The **Key** corresponds to the flag key in your sample app.

Next, create a variable in your flag:

1. In your new flag, `product_sort`, under **Flag Setup**, go to **Variables** and click **Add Variable** (**+**).
2. Select **String** in the **Add Variable** drop-down.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/JFfEO5i9V5tF0Ifv7HdBN_63355e6-add-variable-string.png)

3. Enter *sort\_method* for the **Variable Key**, which corresponds to the variable key in your sample app.
4. Enter *alphabetical* for the **Default Value**, which represents your old sorting method. The new sorting method is what you are rolling out.
5. Click **Save**.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/TmZIBYzEAMbP9XqDp2hp3_19e5365-configure-variable-react.png)

Next, create a variation in your flag:

1. Under **Flag Setup**, go to **Variations** and select the **On** variation. A variation is a wrapper for a collection of variable values.
2. For the **sort\_method** variable value, enter *popular\_first*, which represents your new sorting method.
3. Click **Save**.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/Jw49kI1hBAvmVSgxE1mny_2c6a215-on-variation-popular-first.png)

### 2. Create the flag delivery rule

Your sample app *still* does not do anything because you need to create and enable a [flag rule](docId\:CFAu9P5PdLLMB8GsFn_fo).

Make a [targeted delivery rule](docId\:R0KSPrSRYev0Q6jXL27QK) for the **On** variation for the **product\_sort** flag. A targeted delivery lets you gradually release a feature flag to users, but with the flexibility to roll it back if you encounter bugs.

1. Ensure you are in your primary environment (because you are using the primary environment SDK key from [Part 1](docId\:uUfLuItu1iCv6iAYW8tHO)).

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/RtAsh_IifAIFq35w6NSsR_0a5d0f9-image.png)

2. Click **Add Rule** and select **Targeted Delivery**.
3. Enter *Targeted Delivery* for the **Name** field.
4. Keep the default **Key** and **Audiences**.
5. Set the **Traffic Allocation** slider to 50%. This delivers the **product\_sort** flag to 50% of everyone who triggers the flag in this environment. You can roll out or roll back the **product\_sort** flag to a percentage of traffic whenever you want.
6. From the **Deliver** drop-down list, select the **On** variation.
7. Click **Save**.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/Amt-ksRr-q3urU8UtQsIk_0878a69-image.png)

### 3. Run your sample app

To run your sample application:

1. Click **Run** on your targeted delivery rule:

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/XmGdpCrD9PUacZfMisVdO_de01aa0-image.png)

2. Click **Ok** on the **Ready to Run Status** page. This lets you know that your ruleset has not been set to run, yet.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/_aDAwcuNhUJG50GImI1Aa_7b4d47d-image.png)

3. Click **Run** on your ruleset (flag):

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/_BNsfhXQqfgvuAAZFi609_d2c103d-image.png)

4. Run the React Native application on iOS or Android:

```shell
npx react-native run-ios
```

```shell
npx react-native run-android
```

The output should display in the simulator/emulator similar to the following:

```javascript
Your user ID: 483921
Flag on. You saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: targeted_delivery
```

:::hint{type="info"}
**Note**
Whether the flag is on or off depends on your user ID and the 50% traffic allocation. Close and reopen the app to get a new random user ID and potentially see a different result.
:::

### 4. How it works

So far, you:

- Created a flag, flag variable, and a flag variation (wrapper for your variables) in your Optimizely project.
- Implemented a flag in your app with the **useDecide** hook.

What is going on in your sample app?

### How it works: decide to show a user a flag

The React SDK's [useDecide hook](docId:1QIsG8eFYkYIPmTw6_9aa) determines whether to show or hide the feature flag for a specific user.

:::hint{type="info"}
**Note**
You can reuse this hook for different flag rules -- whether for delivering to more traffic, or running an experiment to show different sorting methods to just a portion of users.
:::

After you learn which sorting method works best to increase sales, roll out the product sort flag to all traffic with the method set to the optimum value.

In your sample app:

```javascript
// "product_sort" corresponds to the flag key you create in the Optimizely app
const { decision, isLoading, error } = useDecide('product_sort');
```

:::hint{type="info"}
**Note**
Include attributes when you create your user (via the `user` prop on `OptimizelyProvider`), so that you can target specific audiences. For example:

```javascript
var attributes = { logged_in: true };

<OptimizelyProvider
  client={optimizelyClient}
  user={{
    id: 'userId',
    attributes: attributes,
  }}>
    { /*Application Components here*/ }
</OptimizelyProvider>
```
:::

### How it works: configure flag variations

You can dynamically configure a flag variation using flag variables. In your sample app:

```javascript
// always returns false until you enable a flag rule in the Optimizely app
if (decision.enabled) 
{
  // "sort_method" corresponds to variable key you define in Optimizely app
 var sortMethod = decision.variables['sort_method'];
 console.log('sort_method: ', sortMethod);
}
```

For your **product\_sort** flag, you can configure variations with different **sort\_method** values, sorting by popular products, relevant products, promoted products, and so on.  You can set different values for the sort method at any time in the Optimizely app.

## Part 3: Run an A/B test

[Part 2](docId\:uUfLuItu1iCv6iAYW8tHO) of this tutorial guided you through a targeted delivery because it is the most straightforward flag rule. However, you often want to [A/B test](docId\:raDQAUQpQJywODzUkXKhZ) how users react to feature flag variations *before* you roll out a flag delivery.

- [Targeted delivery rule](docId\:R0KSPrSRYev0Q6jXL27QK) – You can roll out your flag to a percentage of your general user base (or to specific audiences), or roll back if you encounter bugs.
- [A/B test rule](docId\:raDQAUQpQJywODzUkXKhZ) – Experiment by A/B testing a flag before you invest in delivering, so you know what to build. Track how users behave in flag variations, then interpret your experiment results using the Optimizely Stats Engine.

For Part 3, you will run an A/B test on the **On** variation of your **product\_sort** flag.

### 1. Add event tracking

You need to add event tracking to your sample app, so you can mock up user events and then see [metrics](docId:06YPvA1xY9tK6261dIE66).

1. Delete your old sample code, and paste in the following code.
2. **Replace your SDK key**. See [Get your SDK Key](docId\:uUfLuItu1iCv6iAYW8tHO).
3. Do not run your app yet because you still need to configure the A/B test in the Optimizely application.

```javascript
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import {
  createInstance,
  createPollingProjectConfigManager,
  createBatchEventProcessor,
  OptimizelyProvider,
  useDecide,
  useOptimizelyUserContext,
} from '@optimizely/react-sdk';

const optimizelyClient = createInstance({
  projectConfigManager: createPollingProjectConfigManager({
    sdkKey: 'YOUR_SDK_KEY',
  }),
  eventProcessor: createBatchEventProcessor(),
});

function App() {
  const [userId] = useState(() =>
    (Math.floor(Math.random() * 999999) + 100000).toString()
  );

  return (
    <OptimizelyProvider
      client={optimizelyClient}
      user={{ id: userId }}
    >
      <View style={styles.container}>
        <Text style={styles.text}>Welcome to our Quickstart Guide!</Text>
        <Text style={styles.text}>Your user ID: {userId}</Text>
        <Decision />
        <TrackPurchase />
      </View>
    </OptimizelyProvider>
  );
}

function Decision() {
  const { decision, isLoading, error } = useDecide('product_sort');

  if (isLoading) return <Text style={styles.text}>Loading decision...</Text>;
  if (error) return <Text style={styles.text}>Error: {error.message}</Text>;

  const variationKey = decision.variationKey;
  const sortMethod = decision.variables['sort_method'];

  return (
    <Text style={styles.text}>
      {`Flag ${
        decision.enabled ? 'on' : 'off'
      }. You saw flag variation: ${variationKey} and got products sorted by: ${sortMethod} config variable as part of flag rule: ${
        decision.ruleKey
      }`}
    </Text>
  );
}

function TrackPurchase() {
  const { userContext, isLoading } = useOptimizelyUserContext();
  const [tracked, setTracked] = useState(false);

  if (isLoading) return null;

  const handlePress = () => {
    if (userContext) {
      userContext.trackEvent('purchase');
      setTracked(true);
    }
  };

  return (
    <View>
      {!tracked ? (
        <TouchableOpacity style={styles.button} onPress={handlePress}>
          <Text style={styles.buttonText}>Simulate Purchase</Text>
        </TouchableOpacity>
      ) : (
        <Text style={styles.text}>Purchase event tracked! Check your experiment results.</Text>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 16,
  },
  text: {
    fontFamily: 'monospace',
    fontSize: 14,
    marginBottom: 8,
  },
  button: {
    backgroundColor: '#007AFF',
    padding: 12,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 8,
  },
  buttonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
});

export default App;
```

### 2. Delete other rules in free accounts

If you have a free Optimizely account, you need to delete the Targeted Delivery you created in [Part 2](docId\:uUfLuItu1iCv6iAYW8tHO) before you create your A/B test:

1. Select the **Flag** that contains the Targeted Delivery you created in Part 2 from the Flags tab.
2. Select the primary environment and the Targeted Delivery rule you created in Part 2.
3. Click **More Options** > **Delete**:

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/7Bzb69sbZSZFHT9NTQ4ED_9c4d711-image.png)

4. Click **Save**.

### 3. Create the A/B test

To create an A/B Test rule in your Feature Experimentation project, in the flag you created in [Part 2](docId\:uUfLuItu1iCv6iAYW8tHO):

1. Click **Add Rule** and select **A/B Test**.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/t8JzgOKwAp-ye_AsdtgIa_3a71c79-a-b-test-rule.png)

2. Enter *Experiment* for the **Name** field.
3. Keep the default **Key** and **Audiences**
4. Keep the **Ramp Percentage** traffic allocation slider set to 100%.

### 4. Add an event

In an experiment, you track users' relevant actions to measure how they react to your flag variations. To define the actions you want to track, called [events](docId\:SViQcZpYCosJLYzXIiAhP):

1. Click on the **Metrics** field.
2. Click **Create new event**.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/ABtmFjVvhSrqNwPs7CHLn_b3754e5-create-new-event.png)

3. Enter *purchase* for the **Event Name**, and the **Event Key** is automatically filled.
4. (Optional) Enter a **Description**. You will want to know whether the new sorting flag helps customers figure out what to buy, so track whether the user makes a purchase after they were shown the products in a new order.
5. Click **Create Event**.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/2O2N-P9dfRbsCn8tEcPFs_82c5a42-react-create-event.png)

6. In the **Add Metric** modal, leave the defaults, measure **increase** in **unique conversions**.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/vuD0IhTvtsyWmSCC4Goiz_2bade23-add-metric-react.png)

7. Click **Add Metric**.
8. Leave the default **Off** variation as a control. Select the **On** variation you configured in [Part 2](docId\:uUfLuItu1iCv6iAYW8tHO):

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/CNv7VonmAHhMtwD0xieeR_92c5706-on-variation.png)

:::hint{type="info"}
**Note**
You are not limited to two variations; you can also create A/B tests with multiple variations.
:::

9. Click **Save** to create your A/B Test rule.
10. Click **Run**.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/fDdLaCLlJP_hoKLjtNI54_9ae34f5-image.png)

### 5. Run the A/B test

Ensure your ruleset's (flag's) status is **Running**, and the rule's status is **Running** so your experiment can run:

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/PlkFsMB2R-JpWpSpqy3Hj_cce40a5-image.png)

Run your React Native app:

```shell
npx react-native run-ios
```

```shell
npx react-native run-android
```

You will see the flag decision and a "Simulate Purchase" button. Tap it to track a purchase event for your user.

### 6. See your A/B test results

Go to the [Reports](docId:_K6n7h_MZ8b0xn6yWPrrq) tab and select your experiment to see your results.

![](https://api.archbee.com/api/optimize/BrbvVORKJ5iIeSMZye5kI/NwBQPuQf1p8tP1rQx7ApQ_a2128ff-experiment-results-page.png)

:::hint{type="info"}
- **Note**
  You might not see the exact user traffic percentages you configured for your flag variations until you have larger numbers of users.
- You might not see your user traffic immediately. Refresh the app to refresh traffic.
- Your experiment results will not tell you a winning variation until you have a large number of users (on the order of 100,000).
:::

### 7. How it works

For an A/B test, you need a way to tell Optimizely when a user made a purchase in your app and map this event in your app code to the specific event you created in Optimizely. Use the `useOptimizelyUserContext` hook to get the user context and call `trackEvent`. In your sample app:

```javascript
const { userContext } = useOptimizelyUserContext();

// Track how users behave when they see a flag variation
userContext.trackEvent('purchase');
```

:::hint{type="info"}
**Note**
Optionally add tags to your event to enrich it (not shown in your sample app). You can also use reserve tag keys like **revenue** to track quantitative results. For example:

```javascript
var tags = {
  category: 'shoes',
  revenue: 6432,
};

userContext.trackEvent('purchase', tags);
```
:::

## Conclusion

Congratulations! You configured and launched your first Feature Experimentation experiment on React Native. While this example focused on optimizing sales, Optimizely's experimentation platform can support an open-ended set of experimentation use cases.

See the complete [React Native SDK documentation](docId\:KXNDhDlq6JsnWZ3Uwguc6) to learn more ways to optimize your software using experimentation.
