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.

Since the @statsig/react-bindings works in conjuction with @statsig/js-client, the @statsig/js-client documentation can also be relevant for React implementations.

Installation

You can install the Statsig SDK via npm or yarn:

npm install @statsig/js-client @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, your app should be ready to run. You can optionally provide a 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-YOUR-CLIENT-API"
user={{ userID: "1234", email: "example@statsig.com" }}
>
<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.

Gates

Evaluating a gate is done using the useGateValue hook like this:

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

function RootPage() {
const gateValue = useGateValue("check_user");
return (
<div>Gate is {gateValue ? 'passing' : 'failing'}.</div>
);
}

export default RootPage;

Experiments

You can reach into the experiment variant and access parameters that are assigned to the specific user by using the useExperiment hook like this:

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

function RootPage() {
const experiment = useExperiment("headline_test");
return (
<div>Headline Parameter: {experiment.get('headline', 'Default')}.</div>
);
}

export default RootPage;

Updating user properties

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;

More Hooks

The react-bindings package exposes some hooks for convenience.

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.

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 asynchornously 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.

Client Retriveval 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);

FeatureGate 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 convience 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.

...

DynamicConfig Hooks

  • (recommended): useStatsigClient.getDynamicConfig will trigger an exposure only when called
  • useDynamicConfig is a convience hook that returns the boolean value and is the most basic way to check if a gate is enabled.

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 convience 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 convience hook that returns the layer. This does not log an exposure
...

Log Event Hook

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.

...