Skip to main content

React Native SDK for Statsig

Statsig client side SDK for applications in React Native not using Expo. If you are using Expo, check out our Expo SDK. This SDK is based on our JavaScript client SDK.

Installation

You can install the SDK via npm or yarn. In your project directory, run:

npm install statsig-react-native

Next, let's install the dependencies we need for the SDK to work:

npm install @react-native-async-storage/async-storage react-native-device-info react-native-get-random-values

Lastly, if you are on a Mac and developing for iOS, you need to install the pods to complete the linking:

npx pod-install ios # or pod install, in your /ios folder

Usage

How we at Statsig use the SDK, and suggested usage.

info

NOTE: The statsig-react-native SDK wraps the statsig-react SDK. It contains the same React Context, Providers, and Hooks, used in the same way, HOWEVER you must import from the statsig-react-native package.

It also exposes a global Statsig class that you can import outside your component tree to check gates/log events/etc.

At the root of your component tree, wrap your app in a StatsigProvider and set waitForInitialization=true (if you do not wait for initialization, useGate hooks will return false on the first render, and will only update to the actual gate value once SDK initialization completes and Gates are fetched for the passed in user. Similarly, useConfig and useExperiment will return empty dynamic configs).


import { StatsigProvider } from 'statsig-react-native';

...

<StatsigProvider
sdkKey="<CLIENT_SDK_KEY>"
user={{
userID: <LOGGED_IN_USER_ID>,
email: session?.user?.email ?? undefined,
... // other user parameters
}}
waitForInitialization={true}>
<MyComponent />
</StatsigProvider>

Then, in your app, the useGate, useConfig, and useExperiment hooks will provide the up to date values of Feature Gates, DynamicConfigs, and Experiments (respectively) for the initialized user. If you are unfamiliar with React Hooks, see the rules of hooks.

import { useGate } from 'statsig-react-native';

...

export default function MyComponent(): JSX.Element {
// only call hooks at the top level of a functional component
const featureOn = useGate(<MY_FEATURE_GATE>).value;

return {featureOn ? <MyComponent /> : null;
}
info

NOTE: Statsig SDK Hooks rely on a Context from the Statsig Provider. Context will get its value from the closest matching Provider above it in the component tree. Make sure you make a separate child component to consume the StatsigContext, and place your hooks there. Learn more here: https://reactjs.org/docs/context.html

To logEvents, get the global javascript SDK

import { Statsig } from 'statsig-react-native';

...

export default function MyComponent(): JSX.Element {

return
<Button
onClick={() => {
Statsig.logEvent('button_clicked');
}}
/>;
}

If you need to check gates/configs in a loop, you can use this same import to avoid using the Feature Gate and Config hooks improperly in a loop.

More Details

The statsig-react-native sdk exports the following components:

StatsigProvider

StatsigProvider is a react context provider which initializes the SDK, and passes down its state to the rest of the react application via a StatsigContext. It takes the following properties:

  • children: React.ReactNode | React.ReactNode[]; - One or more child components
  • sdkKey: string; - A client SDK key from the Statsig Console
  • user: StatsigUser; - A Statsig User object. Changing this will update the user and Gate values, causing a re-initialization
  • options?: StatsigOptions; - See StatsigOptions. An optional bag of initialization properties (shared with the statsig-js sdk) for advanced configuration.
  • waitForInitialization?: boolean; - Waits for the SDK to initialize with updated values before rendering child components
  • initializingComponent?: React.ReactNode | React.ReactNode[]; - A loading component to render iff waitForInitialization is set to true and the SDK is initializing
  • mountKey?: string - A key for stable mounting/unmounting when updating the user. If this key is set and changes when the user object changes (or if it is not provided) Then the children of StatsigProvider will unmount/remount with the async update. If this key is set and does not change, then the children of StatsigProvider will continue to be mounted, and it will trigger a rerender after updateUser completes.
  • shutdownOnUnmount?: boolean - If set to true, will automatically call Statsig.shutdown() when the provider is unmounted

Hooks

The SDK exposes Feature Gates, Dynamic Configs, Experiments, and the underlying statsig-js. If you are unfamiliar with hooks, be sure to check out the rules of hooks

useGate

A react hook to get a Statsig Feature Gate.

Parameters:

  • gateName: string - the name of the gate to check

Returns GateResult:

  • isLoading: boolean; - the loading/initializing state of the SDK
  • value: boolean - the value of the feature gate (false by default)
useConfig

A react hook to get a Statsig Dynamic Config.

Parameters:

  • configName: string - the name of the config to get

Returns ConfigResult:

  • isLoading: boolean; - the loading/initializing state of the SDK
  • config: DynamicConfig - the backing DynamicConfig (see the statsig-js sdk docs for more information)
useExperiment

A react hook to get a Statsig Experiment, represented as a DynamicConfig.

Parameters:

  • experimentName: string - the name of the experiment to get

Returns ConfigResult:

  • isLoading: boolean; - the loading/initializing state of the SDK
  • config: DynamicConfig - the backing DynamicConfig (see the statsig-js sdk docs for more information)
useLayer

A react hook to get a Statsig Experiment, represented as a DynamicConfig.

Parameters:

  • experimentName: string - the name of the experiment to get

Returns LayerResult:

  • isLoading: boolean; - the loading/initializing state of the SDK
  • layer: Layer - the backing Layer (see the statsig-js sdk docs for more information)
useStatsigLogEffect

A react hook to simplify top level logEvents into an effect which will only log and event once the SDK is ready

Parameters: none

  • eventName: string
  • value?: string | number | null
  • metadata?: Record<string, string> | null
StatsigContext

StatsigContext is a react context used internally by the SDK to manage internal state. You should not need to use the StatsigContext directly, as the Provider and Hooks interface with it for you. It tracks the following state:

  • initialized: boolean; the initialization state of the SDK
  • statsigPromise: React.MutableRefObject<Promise<void>> | null; a reference to a promise which resolves once SDK initialization is complete
  • initStarted: boolean whether the singleton Statsig has had initialize called on it, meaning the SDK is now usable and can serve checks from cache and queue log events
  • userVersion: number used interally by the SDK to memoize SDK functions based on the user. Increments when the user object is changed and updateUser is called.
Statsig

You can import the global Statsig singleton to call SDK functions outside of a component tree or in callbacks/loops/or wherever else you are unable to use hooks. For all SDK functions, see the statsig-js sdk docs.

info

If you are calling methods on the global Statsig like initialize or updateUser, the user object tracked by the provider and the user object used outside the component tree can get out of sync. You are responsible for maintaining the state of the user and keeping it consistent with the StatsigProvider in these cases. The statsig-react-native SDK uses the global Statsig class to serve gate/config/experiment checks, but these are memoized in the hooks the SDK provides. Updates to the user which impact flag values that are made outside the context of the react component tree will not be reflected in the component tree unless the updated user is passed in to the StatsigProvider.

import { Statsig } from "statsig-react-native";

...

Statsig.checkGate("gate_name");

StatsigOptions

  • environment: StatsigEnvironment, default null
    • An object you can use to set environment variables that apply to all of your users in the same session and will be used for targeting purposes.
    • The most common usage is to set the environment tier ('production', 'staging' or 'development'), e.g. { tier: 'staging' }, and have feature gates pass/fail for specific environments.
  • disableCurrentPageLogging boolean, default false.
    • By default, the sdk appends the current page for log events to the event payload to generate user journey/funnel analytics
  • loggingIntervalMillis: number, default 5000 (5s), min 1000, max 60000
    • How frequently to flush logs to statsig (milliseconds)
  • loggingBufferMaxSize: number, default 10), min 2, max 500
    • Maximum number of events to buffer before flushing events to statsig
  • disableNetworkKeepalive: boolean, default false
    • Entirely disables the keepalive flag from being appended to network requests issued by the SDK
  • api - default https://api.statsig.com/v1/
    • The default endpoint to use for all SDK network requests. You should not override this (unless you have another API that implements the Statsig API endpoints)
    • If you wish to separately override the log_event endpoint only, see eventLoggingApi
  • overrideStableID - string, default null
    • If you'd like to use your own ID in place of Statsig's stableID, then you can pass the ID as an option here.
    • Once a value is passed, the SDK will store this ID in the local storage for the browser for future use as well.
  • localMode - boolean, default false
    • Pass true to this option to turn on Local Mode for the SDK, which will stop the SDK from issuing any network requests and make it only operate with only local overrides and cache.
  • initTimeoutMs - number, default 3000
    • This option configures the maximum time (in milliseconds) the SDK would wait for the network request made by initialize() to respond before it resolves.
    • If the SDK resolves before the network request has completed due to the timeout, it will continue work with local overrides, cached values, and then default values set in code.
  • disableErrorLogging - boolean, default false
    • By default, the SDK auto logs javascript errors to Statsig. This will be connected with the metrics and pulse views to show the impact of new features on key error metrics
  • disableAutoMetricsLogging - boolean, default false
    • By default, the SDK auto logs javascript performance metrics to Statsig. This will be connected with the metrics and pulse views to show the impact of new features on key performance metrics
  • eventLoggingApi? string, default 'https://events.statsigapi.net/v1/
    • The SDK will hit different endpoints for initialize to evaluate gates and for logEvent to log event data. The api option controls the evaluation endpoint, and eventLoggingApi controls the event logging endpoint.
  • prefetchUsers? StatsigUser[] | null, default null
    • An array of additional StatsigUser objects to be fetched during the statsig.initialize call. A max of 5 users is enforced, if more than 5 users are provided, the 5 users at the start of the array will be used.

FAQ

Some users of the react native SDK have reported issues that look like the following:

 ERROR  [Statsig] An unexpected exception occurred. [TypeError: undefined is not a function (near '...}).finally(function () {...')]

Some libraries, like storybook, remove the finally() handler for promises. In order to pollyfill this and get around the error, see this thread:

https://github.com/storybookjs/react-native/issues/20