How to add feature flags and experiments to a React Native app

Fetch a native report-layout variant, show its assigned UI, and record exposure after the report renders. Use Report Exported as the experiment metric.

  • React Native 0.88
  • Community CLI
  • Experiment plugin beta.12
  • 30 min

Chris Tam · Last updated 11 November 2026

A report layout can change how easily someone finds the export action. I use Amplitude feature flags and experimentation to compare a short report with one that adds a summary.

In this tutorial, you'll configure a client deployment, fetch a report variant, record exposure after rendering, and check the export metric.

A report screen that renders control or expanded when assigned, keeps a baseline when no assignment exists, and tracks Report Exported against the rendered variant. It sends no exposure for the local fallback.

Prerequisites

  • React Native 0.88.0 and React 19.3.0 with the New Architecture. Node.js 22.13+ in the 22.x series, 24.3+ in the 24.x series, or 26+; Corepack and pnpm 10.33.2.
  • An Android device/emulator and its development tools, or macOS with Xcode, an iOS device/simulator, Bundler and CocoaPods. Follow React Native environment setup.
  • A separate Amplitude development project, its public project API key from Settings > Projects > your project > General, and its US or EU data center. The app uses a fixed synthetic test identity; host apps use verified authentication.
  • Access and allowance for Feature Experiment, a client deployment key and a remote-evaluation flag. Use a bare native project or an Expo development/native build, not Expo Go.

Sign up for Amplitude if you need a project, and compare plans for your product allowances. Use synthetic data throughout this walkthrough.

The React Native Experiment Analytics plugin is early access. The sample pins 1.0.0-beta.12 exactly and does not assume compatibility with another beta release.

1. Create the native app and install dependencies

I use the Community CLI to create the native Android and iOS projects. This page includes the complete custom files for a fresh app; another Build tutorial is optional context. In an existing app, merge dependencies and instrumentation into the current project while preserving its framework, native settings, authentication, routing and enabled products.

The mobile SDK quickstart supplies Analytics and AsyncStorage. The product SDK reference supplies the plugin. The standalone app pins released versions for reproducibility.

Terminal
mkdir -p amplitude-react-native/tooling
tooling/package.json
{
  "name": "react-native-build-tooling",
  "private": true,
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8"
}
tooling/pnpm-workspace.yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
Terminal
cd amplitude-react-native/tooling
pnpm --config.minimumReleaseAge=10080 --config.trustPolicy=no-downgrade dlx @react-native-community/cli@20.2.0 init AmplitudeReports --version 0.88.0 --skip-install --skip-git-init
cd AmplitudeReports

Keep the generated android/, ios/ and Gemfile. The CLI separately downloads its native template; the pnpm safeguards govern the fetched CLI package and the app dependency install, not that internal template download. Save the following files in AmplitudeReports.

Terminal
mkdir -p src __tests__
package.json
{
  "name": "AmplitudeReports",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "typecheck": "tsc --noEmit",
    "bundle:android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output artifacts/index.android.bundle --assets-dest artifacts/android",
    "bundle:ios": "react-native bundle --platform ios --dev false --entry-file index.js --bundle-output artifacts/main.jsbundle --assets-dest artifacts/ios"
  },
  "dependencies": {
    "react": "19.3.0",
    "react-native": "0.88.0",
    "@react-native/new-app-screen": "0.88.0",
    "react-native-safe-area-context": "^5.5.2",
    "@amplitude/analytics-react-native": "1.13.0",
    "@react-native-async-storage/async-storage": "2.1.2",
    "@amplitude/plugin-experiment-react-native": "1.0.0-beta.12"
  },
  "devDependencies": {
    "@babel/core": "^7.25.2",
    "@babel/preset-env": "^7.25.3",
    "@babel/runtime": "^7.25.0",
    "@react-native-community/cli": "20.2.0",
    "@react-native-community/cli-platform-android": "20.2.0",
    "@react-native-community/cli-platform-ios": "20.2.0",
    "@react-native/babel-preset": "0.88.0",
    "@react-native/jest-preset": "0.88.0",
    "@react-native/metro-config": "0.88.0",
    "@react-native/typescript-config": "0.88.0",
    "@types/jest": "^29.5.13",
    "@types/react": "^19.2.0",
    "@types/react-test-renderer": "^19.1.0",
    "jest": "^29.6.3",
    "react-test-renderer": "19.3.0",
    "typescript": "^6.0.3"
  },
  "engines": {
    "node": "^22.13.0 || ^24.3.0 || >=26.0.0",
    "pnpm": ">=10.21.0"
  },
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8"
}
pnpm-workspace.yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
nodeLinker: hoisted
overrides:
  "semver@6.3.1": "7.8.5"
.gitignore
node_modules/
artifacts/
.env*
ios/Pods/
android/.gradle/
android/app/build/
app.json
{
  "name": "AmplitudeReports",
  "displayName": "AmplitudeReports"
}
index.js
/**
 * @format
 */

import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);
babel.config.js
module.exports = {
  presets: ['module:@react-native/babel-preset'],
};
metro.config.js
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

/**
 * Metro configuration
 * https://reactnative.dev/docs/metro
 *
 * @type {import('@react-native/metro-config').MetroConfig}
 */
const config = {};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);
tsconfig.json
{
  "extends": "@react-native/typescript-config",
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": ["**/node_modules", "**/Pods"]
}
jest.config.js
module.exports = {
  preset: '@react-native/jest-preset',
};

The workspace retains the explicit semver 6.3.1 to 7.8.5 override tested with this scaffold. Retest that major-version override when updating Babel or React Native. Optional template lint tooling is omitted; preserve your lint setup in an existing app. Keep release-age and trust safeguards enabled if installation reports a dependency problem.

Terminal
pnpm install
# Commit the generated pnpm-lock.yaml; repeat installs with:
pnpm install --frozen-lockfile

2. Configure one client and the product plugin

I keep the project key in one explicit client configuration file. Project API keys ship in a mobile binary; secret management and server deployment keys stay on the backend. Set apiKey and serverZone for the development project. The fixed demoUserId identifies synthetic activity only. Replace it with the confirmed account from your authentication system when merging into a signed-in app.

Set deploymentKey to a public client deployment key from that same project. Use the exact report-layout key configured in step 4.

src/amplitude-config.ts
// Public client configuration for a separate development project.
// Never put a secret management key in a mobile application.
export const config = {
  "apiKey": "",
  "serverZone": "US" as "US" | "EU",
  "demoUserId": "build-rn-feature-flags-demo",
  "deploymentKey": "",
  "flagKey": "report-layout"
};
src/instrumentation.ts
// Keep existing replay, engagement, consent and verified identity when merging.
import * as amplitude from '@amplitude/analytics-react-native';
import {experimentPlugin} from '@amplitude/plugin-experiment-react-native';
import {config} from './amplitude-config';

let ready: Promise<boolean> | undefined;
let enabled = false;
let plugin: ReturnType<typeof experimentPlugin> | undefined;
export type Decision = {value: 'control' | 'expanded' | 'fallback'; assigned: boolean};

export function startDemo(): Promise<boolean> {
  if (!ready) {
    ready = (async () => {
      if (!config.apiKey.trim() || !config.deploymentKey.trim() || !['US', 'EU'].includes(config.serverZone)) return false;
      await amplitude.init(config.apiKey, config.demoUserId, {
        serverZone: config.serverZone, autocapture: false,
      }).promise;
      plugin = experimentPlugin({deploymentKey: config.deploymentKey, automaticExposureTracking: false});
      await amplitude.add(plugin).promise;
      const client = plugin.experiment;
      if (!client) return false;
      await client.start();
      enabled = true;
      return true;
    })().catch(() => false);
  }
  return ready;
}

export function reportDecision(): Decision {
  if (!enabled) return {value: 'fallback', assigned: false};
  const value = plugin?.experiment?.variant(config.flagKey).value;
  return value === 'control' || value === 'expanded'
    ? {value, assigned: true} : {value: 'fallback', assigned: false};
}

export function exposeReport(decision: Decision): void {
  if (enabled && decision.assigned) plugin?.experiment?.exposure(config.flagKey);
}

export function recordExport(decision: Decision): void {
  if (ready) void ready.then(enabled => {
    if (enabled) void amplitude.track('Report Exported', {
      report_type: 'usage', report_variant: decision.value,
    }).promise.catch(() => undefined);
  });
}

The shared ready promise prevents parallel Start actions from creating more than one client. A blank configuration leaves the local report usable. Failed setup stays failed until an app restart; check SDK logs and fix the configuration before retrying. An initialization promise is a local ordering signal, not proof of ingestion or a native product result.

The plugin creates the Experiment integration around this Analytics instance. Do not also call an Experiment initializer. start() loads startup variants; variant() reads them. The app reads no variants until startup succeeds. A rejected startup keeps the local fallback even if the client has cached values. The app disables automatic exposure so its render effect can report exposure only for assigned UI.

MCP. An optional Amplitude MCP connection can help your coding agent inspect existing event names. It uses account permissions independently of this app's ingestion key. Keep an established Report Exported event name if your project already has one.

3. Add the native report screen

I keep local report behavior independent of uploads. Save this complete screen for the standalone app. For an existing application, merge its controls into the current screen and preserve the current root, navigation and lifecycle handlers.

App.tsx
import React, {useEffect, useState} from 'react';
import {Button, ScrollView, Text, View} from 'react-native';
import {SafeAreaProvider, SafeAreaView} from 'react-native-safe-area-context';
import {Decision, exposeReport, recordExport, reportDecision, startDemo} from './src/instrumentation';

export default function App() {
  const [status, setStatus] = useState('Demo stopped. Baseline report remains available.');
  const [busy, setBusy] = useState(false);
  const [opened, setOpened] = useState(false);
  const [decision, setDecision] = useState<Decision>({value: 'fallback', assigned: false});
  const [exports, setExports] = useState(0);
  useEffect(() => {if (opened) exposeReport(decision);}, [opened, decision]);
  async function start() {
    setBusy(true);
    try {setStatus(await startDemo() ? 'SDK setup completed. Open the report to check assignment.' : 'Check keys, deployment and SDK logs, then restart.');}
    finally {setBusy(false);}
  }
  function open() {
    setDecision(reportDecision());
    setOpened(true);
  }
  return <SafeAreaProvider><SafeAreaView style={{flex: 1, backgroundColor: '#FFFFFF'}}>
    <ScrollView contentContainerStyle={{padding: 24, gap: 16}}>
      <Text style={{fontSize: 28, color: '#000000'}}>Usage report</Text>
      <Button title="Start demo" onPress={() => {void start();}} disabled={busy || opened} />
      <Button title="Open report" onPress={open} disabled={busy || opened} />
      {opened && <View testID="report-layout">
        <Text>Report layout: {decision.value}</Text>
        <Text>84 report actions in seven days.</Text>
        {decision.value === 'expanded' && <Text>12 exports across eight active accounts.</Text>}
        <Button title="Export report" onPress={() => {setExports(n => n + 1); recordExport(decision);}} />
        <Text>Local exports: {exports}</Text>
      </View>}
      <Text accessibilityRole="alert">{status}</Text>
    </ScrollView>
  </SafeAreaView></SafeAreaProvider>;
}

The report opens once per mounted example. React's effect runs after that assigned layout commits. Reopening a report in a real router needs an explicit view lifetime; retain that boundary and review StrictMode behavior when expanding the example.

4. Configure the development project

I create the deployment and report flag in a development project before testing an assignment. Follow the Experiment quick start and deployment setup.

  1. Open Experiment > Deployments, create a client-side deployment in the Analytics project used by the app, and copy its client key into config.deploymentKey. Server deployment keys stay off mobile devices.
  2. Open Experiment > Feature Flags and create a remote-evaluation flag named Report layout. Confirm its key is report-layout, attach the client deployment, and create variants with the exact values control and expanded.
  3. Limit test targeting to the standalone synthetic user or your approved test identities. Configure a real assignment, activate the development flag, restart the app, and choose Start demo before Open report. Check each variant through an explicit development targeting change; do not rotate production IDs to force assignment.
  4. To measure an A/B test, create an experiment or convert the flag to an experiment, retain the two variant values, and choose Report Exported as the success metric. Review audience, allocation and the exposure definition before starting the development experiment.
Flag contract
{
  "key": "report-layout",
  "variants": ["control", "expanded"],
  "metric_event": "Report Exported"
}

The SDK integration sends the exposure through Analytics. This app disables automatic exposure on variant() and explicitly calls exposure() after an assigned report commits to the screen. The fallback remains a local baseline and is excluded from this exposure path. Keep assignment, exposure and the export metric separate when assessing the result.

5. Check and run the native app

I include focused tests for the JavaScript adapter. They mock SDK boundaries, so they test application ordering and event decisions without real keys or native services. Native capture, flag evaluation and saved survey responses require the separate verification below.

__tests__/instrumentation.test.ts
function setup(key = 'synthetic-key', zone = 'EU') {
  jest.resetModules();
  const calls: string[] = [];
  const analytics = {
    init: jest.fn(() => {calls.push('init'); return {promise: Promise.resolve()};}),
    add: jest.fn(() => {calls.push('add'); return {promise: Promise.resolve()};}),
    track: jest.fn(() => ({promise: Promise.resolve({code: 200})})),
    getDeviceId: jest.fn(() => 'synthetic-device'), getUserId: jest.fn(() => 'synthetic-user'),
  };
  jest.doMock('@amplitude/analytics-react-native', () => analytics);
  jest.doMock('../src/amplitude-config', () => ({config: {
    apiKey: key, serverZone: zone, demoUserId: 'synthetic-user', deploymentKey: 'synthetic-deployment', flagKey: 'report-layout',
  }}));
  const client = {start: jest.fn(async () => {calls.push('start');}), variant: jest.fn(() => ({value: 'expanded'})), exposure: jest.fn()};
  const factory = jest.fn(() => ({experiment: client}));
  jest.doMock('@amplitude/plugin-experiment-react-native', () => ({experimentPlugin: factory}));
  const api = require('../src/instrumentation');
  return {api, calls, analytics, client, factory};
}
test('blank config returns a baseline without initialization or exposure', async () => {
  const x = setup(''); expect(await x.api.startDemo()).toBe(false);
  const d = x.api.reportDecision(); x.api.exposeReport(d);
  expect(d).toEqual({value: 'fallback', assigned: false}); expect(x.analytics.init).not.toHaveBeenCalled();
  expect(x.client.exposure).not.toHaveBeenCalled();
});
test('one initialization uses manual exposure and starts the client before reading', async () => {
  const x = setup(); await Promise.all([x.api.startDemo(), x.api.startDemo()]);
  expect(x.calls).toEqual(['init', 'add', 'start']);
  expect(x.factory).toHaveBeenCalledWith({deploymentKey: 'synthetic-deployment', automaticExposureTracking: false});
  const d = x.api.reportDecision(); expect(d.value).toBe('expanded'); expect(x.client.exposure).not.toHaveBeenCalled();
  x.api.exposeReport(d); expect(x.client.exposure).toHaveBeenCalledWith('report-layout');
});
test('unknown and missing assignments use baseline without exposure', async () => {
  const x = setup(); await x.api.startDemo(); x.client.variant.mockReturnValue({value: 'unrecognized'});
  const d = x.api.reportDecision(); x.api.exposeReport(d);
  expect(d).toEqual({value: 'fallback', assigned: false}); expect(x.client.exposure).not.toHaveBeenCalled();
});
test('metric event records the rendered decision and no fabricated exposure', async () => {
  const x = setup(); await x.api.startDemo(); x.api.recordExport({value: 'control', assigned: true}); await Promise.resolve();
  expect(x.analytics.track).toHaveBeenCalledWith('Report Exported', {report_type: 'usage', report_variant: 'control'});
  expect(x.client.exposure).not.toHaveBeenCalled();
});
test('a rejected startup cannot expose a cached assignment', async () => {
  const x = setup();
  x.client.start.mockRejectedValueOnce(new Error('offline startup'));
  expect(await x.api.startDemo()).toBe(false);
  const d = x.api.reportDecision();
  x.api.exposeReport(d);
  expect(d).toEqual({value: 'fallback', assigned: false});
  expect(x.client.variant).not.toHaveBeenCalled();
  expect(x.client.exposure).not.toHaveBeenCalled();
});
Terminal
pnpm typecheck
pnpm test --runInBand
mkdir -p artifacts
pnpm bundle:android --max-workers 2
pnpm bundle:ios --max-workers 2

Metro bundles check the JavaScript graph for both platforms. They do not compile the Android or iOS native project. Build a native app after installing the plugin; Fast Refresh cannot link new native modules.

Terminal, Android
pnpm start
# In another terminal inside AmplitudeReports:
pnpm android
Terminal, iOS on macOS
bundle install
cd ios
bundle exec pod install
cd ..
pnpm start
# In another terminal inside AmplitudeReports:
pnpm ios

Verify it worked

  1. Leave both keys blank and open the report. Confirm the baseline remains usable, the label says fallback, and the app sends no exposure. A fallback is not evidence of a control assignment.
  2. Set the public project key and client deployment key, then restart. Choose Start demo and Open report. Confirm the displayed value matches an assignment from the development flag: control shows the short report; expanded adds the extra summary.
  3. Find build-rn-feature-flags-demo in Amplitude and confirm its experiment exposure belongs to report-layout and the assigned variant. The exposure must correspond to the report actually shown, not an earlier fetch.
  4. Tap Export report and check Report Exported with report_type=usage and report_variant equal to the rendered value. Check [Experiment] Exposure alongside the success event in the experiment's analysis.
  5. Exercise both real assignments with approved test targeting, then test a missing or unrecognized assignment. That case must show the baseline without an exposure. Native cached/offline behavior and the full experiment result need a device and live service check.

For a signed-in host app, block tracked actions while identity changes, clear the previous user's cached variants, set the verified Analytics identity and await a fresh fetch before showing assigned UI. Preserve engagement cleanup and replay/privacy behavior. The standalone demo's fixed synthetic ID is not an authentication implementation.

Troubleshooting

The report always says fallback. Check the exact flag key, client deployment, active flag and test audience. Empty or unrecognized assignments intentionally render the local baseline.

The flag never reaches the app. The flag must be attached to the deployment whose key the app uses. Both deployment and Analytics belong to the same project and region.

Exposure happens before anyone opens the report. Keep automaticExposureTracking false. Read the variant to choose UI, then call exposure only after an assigned report renders.

A signed-out user sees the previous account's layout. Clear cached variants at the confirmed account boundary, synchronize Analytics identity and await a fetch before enabling the new user's tracked UI.

Metro succeeds but the flag never changes. A JavaScript bundle does not test native storage, account targeting or the evaluation service. Verify those on the native app.

FAQ

Is the Experiment plugin generally available?

The React Native Analytics Experiment plugin is early access. This example pins 1.0.0-beta.12 exactly; review and retest its API before upgrading.

Why use a separate fallback label?

The app needs a usable baseline when it has no assignment. Labeling that state fallback prevents the example from treating a local default as a real control assignment.

Does fetching a variant mean the user saw it?

No. This screen records exposure after the assigned report renders. Fetching loads an assignment; rendering shows it; exporting records the business action.

Full code reference

Steps 1 through 3 and the test file in step 5 contain every custom file for this standalone project. The Community CLI supplies the native scaffold and Gemfile. Keep the generated lockfile with the project. The public Amplitude React Native examples provide additional SDK examples; this report screen is the complete implementation shown above.

Hand it to your agent

Give the agent the complete files above and this bounded implementation request.

Agent prompt
Implement this complete React Native report example. Read the current official docs and report source URLs. Inspect the existing app, package manager, native settings, authentication, consent and Amplitude integrations before changing files. Preserve its single Analytics client and existing functionality; do not replace a host app with this standalone scaffold. Use the early-access @amplitude/plugin-experiment-react-native 1.0.0-beta.12 with the existing Analytics client. Set a client deployment key in the same project. Await plugin.experiment.start before reading report-layout. Disable automatic exposure, render control or expanded, then call exposure after commit. Treat unknown/absent assignments as fallback with no exposure. Track Report Exported with the rendered value. Preserve verified identity and clear/refetch at real account changes. Do not invent an assignment or claim an experiment from a local test. Keep the pnpm integrity pin, age/trust settings, lockfile and native rebuild requirements. Never reset identity during anonymous startup or an unresolved login. Report type checks, mocked tests, Metro bundles, native compilation and live product outcomes separately. If sources disagree, record both statements and pause the affected claim until released SDK evidence or its owner resolves it.

What this unlocks

Product analytics records Report Exported under the same test identity as this integration. Keep that event and its properties consistent when connecting the native experience to your report workflow.

Use [Experiment] Exposure to identify users who saw an assigned report, then compare Report Exported as the success metric. Keep local fallback activity outside the assigned exposure population.

Next steps

Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.

Build the native experience, then verify it

Connect your development project and check the real native result before rolling out the integration.