Skip to main content

Statsig in React

info

If you are starting from scratch, please refer to New React App to get a simple React app up and running.

note

Using Next.JS? Check out our Next guides here.

Installation

You can install the Statsig SDK via npm or yarn:

npm install @statsig/react-bindings

Setup

In your App.js file, import StatsigProvider and wrap your app's content within it. Replace the sdkKey with your Client API key, which you can find in the "API Keys" tab on the Statsig console.

import { StatsigProvider } from "@statsig/react-bindings";

function App() {
return (
<StatsigProvider sdkKey="client-KEY">
<div>Hello world</div>
</StatsigProvider>
);
}

export default App;

Adding a user object

At this point, if you run your app, you will get a type error related to the user prop. To fix this, you can add the user object that sets user properties like so:

import { StatsigProvider } from "@statsig/react-bindings";

function App() {
return (
<StatsigProvider
sdkKey="client-KEY"
user={{ userID: "1234", email: "example@statsig.com" }}>
<div>Hello world</div>
</StatsigProvider>
);
}

export default App;

A typical React app

A typical React application will enclose top-level child/children, which means the StatsigProvider will usually wrap a MainPage or RootPage like this:

// App.js
import RootPage from "./RootPage";
import { StatsigProvider } from "@statsig/react-bindings";

function App() {
return (
<StatsigProvider sdkKey="client-KEY" user={{ userID: "1234" }}>
<RootPage />
</StatsigProvider>
);
}

export default App;
// RootPage.js
function RootPage() {
return (
<div>Hello World</div>
);
}

export default RootPage;
info

Advanced: There are a few different ways to initialize the StatsigClient, with trade-offs between latency and up-to-date values. You can read Initialization Strategies to learn more.

The Basics

You can get an instance of the StatsigClient to check gates, experiments, dynamic configs, layers, and log events.

import { useStatsigClient } from "@statsig/react-bindings";

const { client } = useStatsigClient();

See the methods you can call on the client below.

Checking a Feature Flag/Gate

You can evaluate a gate by getting the client with the useStatsigClient hook, and then calling checkGate

const { client } = useStatsigClient();
return (
<div>Gate is {client.checkGate('check_user') ? 'passing' : 'failing'}.</div>
);

Getting a DynamicConfig

You can get a DynamicConfig value by getting the client with the useStatsigClient hook, and then calling getConfig

const { client } = useStatsigClient();
const config = client.getConfig('app_properties');

return (
<div>{config.get('title', 'Default Title')}</div>
);

Logging an Event

You can get the client with the useStatsigClient hook, and then call logEvent

const { client } = useStatsigClient();
return <button onClick={() => client.logEvent("button_click")}>Click Me</button>

Getting an Experiment

You can access the experiment variant and parameters for the user by getting the client with the useStatsigClient hook, and then calling getExperiment.

const { client } = useStatsigClient();
const experiment = client.getExperiment('headline_test');

return (
<div>Headline Parameter: {experiment.get('headline', 'Default')}.</div>
);

Getting a Layer

You can access layers and layer parameters for the user by getting the client with the useStatsigClient hook, and then calling getLayer.

const { client } = useStatsigClient();
const layer = client.getLayer('homepage_layer');

return (
<div>Headline Parameter: {layer.get('hero_text', 'Welcome')}.</div>
);

Updating user properties (e.g., Login)

Sometimes you'll need to update user properties, say when the user logs in and a userID is assigned, or a set of new properties have been identified. This would require Statsig to go fetch new values for all the gates, experiments and config evaluations. This is achieved by the useStatsigUser hook:

// RootPage.js
import { useGateValue, useStatsigUser } from "@statsig/react-bindings";

function RootPage() {
const gateValue = useGateValue("check_user");
const { updateUserAsync } = useStatsigUser();

return (
<div>
<div>Gate is {gateValue ? 'passing' : 'failing'}.</div>
<button onClick={() => updateUserAsync({ userID: "2" })}>
Login
</button>
</div>
);
}

export default RootPage;

Loading State

Dependent on your setup, you may want to wait for the latest values before checking a gate or experiment. If you are using the StatsigProvider, you can pass in a loadingComponent prop to display a loading state while the SDK is initializing. If you are using the useClientAsyncInit hook, you can check the isLoading prop to determine if the SDK is still loading.

export function App() {
const loadingComponent = <div>Loading...</div>;

return (
<StatsigProvider
...
loadingComponent={loadingComponent} // <- Pass in the loading component
>
<YourComponent />
</StatsigProvider>
);
}

React Hooks

caution

When a hook is called to fetch a value, an exposure log is automatically triggered. If the check only happens conditionally, or later in a dialog, you will over expose your experiment!

We recommend using the useStatsigClient hook for these cases where you need the value conditionally, and then issuing the check inline later. Read on for more details.

Feature Gate Hooks

There are three different ways to check a gate using hooks:

  • (recommended): useStatsigClient.checkGate is the safest way to check a gate, as it forces you to issue the check (and hence log the exposure) as close to the actual difference in experience as possible
  • useGateValue is a convenience hook that returns the boolean value and is the most basic way to check if a gate is enabled.
  • useFeatureGate returns the FeatureGate object, if you need to check more information about the gate.

Note: useGateValue and useFeatureGate will log an exposure on render. useStatsigClient.checkGate will log an exposure when the function is called.

...

Dynamic Config Hooks

  • (recommended): useStatsigClient.getDynamicConfig will trigger an exposure only when called
  • useDynamicConfig returns a DynamicConfig object and logs an exposure on render

Note: useDynamicConfig will log an exposure on render. useStatsigClient.getDynamicConfig will log an exposure when the function is called.

...

Experiment Hooks

  • (recommended): useStatsigClient.getExperiment is the safest way to check an experiment, as it forces you to issue the check (and hence log the exposure) as close to the actual difference in experience as possible
  • useExperiment is a convenience hook that returns the experiment and logs an exposure on render
...

Layer Hooks

  • (recommended): useStatsigClient.getLayer in line with our other recommendations, but matters less for layers as exposures are triggered only when calling .get on a parameter
  • useLayer is a convenience hook that returns the layer. This does not log an exposure
...

Log Event

Using the useStatsigClient hook, it is possible to get hold of the logEvent function.

...

StatsigUser Hook

This hooks provides a way to get the current StatsigUser as well as providing methods for updating that user.

...

Client Retrieval Hooks

While there are all the other hooks documented here for get values/configurations, sometimes you still need to access the StatsigClient directly.

To get the StatsigClient instance that is being used inside a StatsigProvider, you can call the useStatsigClient hook. This will return an object containing the client (StatsigClient) instance as well as the other hoisted functions outlined below.

import {
useStatsigClient,
} from '@statsig/react-bindings';

// Get the Client instance
const { client } = useStatsigClient();

// Call any arbitrary function on StatsigClient
console.log("stableID", client.getContext().stableID);

The client instance that is returned is the StatsigClient defined in the @statsig/js-client package. Refer to that documentation for full methods

Client Initialization Hooks

To make setup easier, there are a few different hooks provided. These should be used outside of the StatsigProvider and should only need to be used once.

  • (recommend): useClientAsyncInit - Returns a client that asynchronously fetches the latest values from Statsig.
  • useClientBootstrapInit - Returns a client loaded with the values provided to through the hook. Values can be generated through the use of a Statsig server SDK.

Note: You do not need to use the provided hooks to initialize a StatsigClient, and instead can opt to write you own initialization logic. See Initialization Strategies.

Testing

When writing tests for your React components, you can use jest to mock Statsig packages.

Consider the following component. We render a simple app that checks a single gate and gets an experiment value.

...

In our jest test, we can mock the underlying hooks being used in the component to return the values we want.

...

Session Replay

By including the @statsig/session-replay package in your project, you can automatically capture and log user sessions as videos. This feature is useful for debugging and understanding user behavior. Read more about Session Replay.

...

Web Analytics / Auto Capture

By including the @statsig/web-analytics package in your project, you can automatically capture common web events like clicks and page views. Read more about Web Analytics.

...