React in Statsig
Supported Features
💡 Tip: Get started quickly with one of our sample apps!
If you are starting from scratch, please refer to New React App to get a simple React app up and running. If you're looking for Next.JS, then check our Next guides here.
AI-powered Setup
Setup Statsig in 90 seconds by using one of these two options:
Run this wizard command in your terminal
npx @statsig/wizard@latest
Installation
You can install the Statsig SDK via npm or yarn:
- NPM
- Yarn
npm install @statsig/react-bindings
yarn add @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. The user prop is a collection of properties that you want to target in for feature gates and experiments, or metadata to slice your experiment results and event logging. See the User (StatsigUser) doc for more information. 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;
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.
- StatsigProvider
- useClientAsyncInit
export function App() {
const loadingComponent = <div>Loading...</div>;
return (
<StatsigProvider
...
loadingComponent={loadingComponent} // <- Pass in the loading component
>
<YourComponent />
</StatsigProvider>
);
}
export function App() {
const { client, isLoading } = useClientAsyncInit(...);
if (isLoading) {
return <div>Loading...</div>;
}
return (
<StatsigProvider client={client}>
<YourComponent />
</StatsigProvider>
);
}
React Hooks
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.checkGateis 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 useGateValueis a convenience hook that returns the boolean value and is the most basic way to check if a gate is enabled.useFeatureGatereturns theFeatureGateobject, if you need to check more information about the gate.
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.getDynamicConfigwill trigger an exposure only when called useDynamicConfigreturns a DynamicConfig object and logs an exposure on render
useDynamicConfig will log an exposure on render. useStatsigClient.getDynamicConfig will log an exposure when the function is called.
Experiment Hooks
- (recommended):
useStatsigClient.getExperimentis 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 useExperimentis a convenience hook that returns the experiment and logs an exposure on render
Layer Hooks
- (recommended):
useStatsigClient.getLayerin line with our other recommendations, but matters less for layers as exposures are triggered only when calling.geton a parameter useLayeris a convenience hook that returns the layer. This does not log an exposure
Parameter Store Hooks
- (recommended):
useStatsigClient.getParameterStorewill trigger an exposure only when calling.get()on a parameter useParameterStoreis a convenience hook that returns the parameter store. It will will trigger an exposure only when calling.get()on a parameter
Example Usage:
import { useParameterStore } from '@statsig/react-bindings';
function MyComponent() {
const store = useParameterStore('my_parameter_store');
// Get parameters with fallback values - exposure logged here
const title = store.get('page_title', 'Default Title');
const maxItems = store.get('max_items', 10);
const isEnabled = store.get('feature_enabled', false);
// Disable exposure logging if needed
const storeNoExposure = useParameterStore('my_parameter_store', {
disableExposureLog: true
});
return <div>{title}</div>;
}
For more information about Parameter Stores, see Parameter Stores Concepts.
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.
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.
Using Persistent Evaluations
If you want to ensure that a user's variant stays consistent while an experiment is running, regardless of changes to allocation or targeting, you can use Persistent Assignment, which lets you plug-in a storage solution to persist historical evaluations for a user.
Implementing in React is similar to the Javascript Usage, and you can also refer to our examples on Github.