(deprecated) statsig-react client sdk
To get started with Statsig in React, you should use the new Statsig React SDK
.
This version of the SDK is deprecated and will only receive major bug fixes going forward. Official support ends Jan 31, 2025.
If you already use this deprecated version, you should check out the migration docs.
Installation
NOTE: v2.X.X+ of the SDK updated the default domains that the SDK hits for initialization and event logging.
To initialize, the SDK will hit: https://featureassets.org To log events, the SDK will hit: https://prodregistryv2.org
Consider if you need to allow these domains in your CSP, VPN, or any other services when updating to this SDK version.
You can install the Statsig React SDK via npm or yarn.
- NPM
- Yarn
npm install statsig-react
yarn add statsig-react
Initialize the SDK
After installation, you will need to initialize the SDK using a Client SDK key from the "API Keys" tab on the Statsig console.
These Client SDK Keys are intended to be embedded in client side applications. If need be, you can invalidate or create new SDK Keys for other applications/SDK integrations.
Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console.
In addition to the SDK key, you should also pass in a StatsigUser for feature gate targeting and experimentation grouping purposes.
At the root of your component tree, wrap your app in a StatsigProvider
and set waitForInitialization=true
.
import { StatsigProvider } from "statsig-react";
function App() {
return (
<StatsigProvider
sdkKey="<STATSIG_CLIENT_SDK_KEY>"
waitForInitialization={true}
// StatsigOptions (Not Required)
options={{
environment: { tier: "staging" },
}}
>
<div className="App">{/* Rest of App ... */}</div>
</StatsigProvider>
);
}
If you do not use waitForInitialization
, all checks to Statsig will return default values until initialization completes.
Working with the SDK
Checking a Feature Flag/Gate
Now that your SDK is initialized, let's check a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;
) by default.
import { useGate } from "statsig-react";
...
function MyComponent() {
const { value, isLoading } = useGate("a_gate_name");
// Only required if you have not set waitForInitialization to true
if (isLoading) {
return <div>Fetching Values...</div>;
}
return <div>{value ? "Passes Gate" : "Fails Gate"}</div>;
}
Reading a Dynamic Config
Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:
import { useConfig } from "statsig-react";
...
function MyComponent() {
const { config, isLoading } = useConfig("a_config_name");
// Only required if you have not set waitForInitialization to true
if (isLoading) {
return <div>Fetching Values...</div>;
}
return <div>{config.get("header_label", "Welcome")}</div>;
}
Getting an Layer/Experiment
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker iterations with parameter reuse.
- useLayer
- useExperiment
import { useLayer } from "statsig-react";
...
function MyComponent() {
const { layer, isLoading } = useLayer("a_layer");
// Only required if you have not set waitForInitialization to true
if (isLoading) {
return <div>Fetching Values...</div>;
}
return (
<div>
<h1>{layer.get("title", "Welcome to Statsig!")}</h1>
<p>{layer.get("discount", 0.1)}</p>
</div>
);
}
import { useExperiment } from "statsig-react";
...
function MyComponent() {
const { config: firstExperiment, isLoading } = useExperiment("first_experiment");
const { config: secondExperiment } = useExperiment("second_experiment");
// Only required if you have not set waitForInitialization to true
if (isLoading) {
return <div>Fetching Values...</div>;
}
return (
<div>
<h1>{firstExperiment.get("title", "Welcome to Statsig!")}</h1>
<p>{secondExperiment.get("discount", 0.1)}</p>
</div>
);
}
Logging an Event
Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig - simply call the Log Event API for the event, and you can additionally provide some value and/or an object of metadata to be logged together with the event:
import { Statsig } from "statsig-react";
Statsig.logEvent("add_to_cart", "SKU_12345", {
price: "9.99",
item_name: "diet_coke_48_pack",
});
// or via a React Hook
import { useStatsigLogEffect } from "statsig-react";
function MyComponent() {
useStatsigLogEffect("my_custom_event", "SKU_12345", {
price: "9.99",
item_name: "diet_coke_48_pack",
});
return <div>...</div>;
}
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.
Statsig User
You should provide a StatsigUser object whenever possible when initializing the SDK, passing as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks).Most of the time, the userID
field is needed in order to provide a consistent experience for a given
user (see logged-out experiments to understand how to correctly run experiments for logged-out
users).
Besides userID
, we also have email
, ip
, userAgent
, country
, locale
and appVersion
as top-level fields on
StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom
field and be able to
create targeting based on them.
const [user, setUser] = useState({
userID: "a-user",
email: "user-a@gmail.com"
});
...
// Pass your StatsigUser into the StatsigProvider
return (
<StatsigProvider
sdkKey="client-key"
waitForInitialization={true}
user={user}
>
Private Attributes
Have sensitive user PII data that should not be logged? No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes
, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes
will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server.
For example, if you have feature gates that should only pass for users with emails ending in "@statsig.com", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" }
to privateAttributes
on the user and that's it!
Updating the StatsigUser
If/when the user object changes, the SDK will automatically fetch the updated values for the new user object -
if waitForInitialization
is false, and no mountKey is set on the StatsigProvider, this will trigger a
re-render for the new user with default values, followed by a render when the values have been updated.
const [user, setUser] = useState({userID: 'initial-user'});
return (
<StatsigProvider
sdkKey="CLIENT_KEY_HERE"
waitForInitialization={false}
user={user}
>
<GateTwo />
</StatsigProvider>
);
// Some time later
setUser({ userID: "another-user" });
If you do not want to pass your setUser
function down to the component that needs to update the user, you can use the provided useUpdateUser
hook to pull it off of the StatsigContext
.
const [user, setUser] = useState({userID: 'initial-user'});
return (
<StatsigProvider
sdkKey="CLIENT_KEY_HERE"
waitForInitialization={false}
user={user}
setUser={setUser} // <-- This is required for the hook to work
>
<GateTwo />
</StatsigProvider>
);
// Some time later
import { useUpdateUser } from "statsig-react";
const updateUser = useUpdateUser(); // <-- This retrieves the same setUser function given to the StatsigProvider
updateUser({ userID: "another-user" });
There's also an updateUser
method on the Statsig interface, but calling this directly may lead to issues with the StatsigProvider.
Fetch Mode v1.26.0+
In some advanced use cases, you may want to limit the number of network requests to be fired during updates to the current user.
Since version 1.26.0, the React SDK supports
StatsigOptions.fetchMode. Setting this option
will change the behavior of Statsig.updateUser
.
The supported FetchModes are as follows:
-
network-only
- This is the default behavior. The SDK will always fetch the latest feature gate and experiment values from the Statsig servers whenStatsig.updateUser
is called. -
cache-or-network
- When set to this mode, the SDK will first check if a cached value exists for the user and was cached during this session (AfterStatsig.initialize
). If no valid cache value is found, a network request will be made to fetch the latest values.
Server Side Rendering
Starting in v1.9.1
, the react SDK supports server side rendering via the StatsigSynchronousProvider
.
This provider takes in similar properties to the StatsigProvider
with a few exceptions:
-
the addition of an
initializeValues
prop, which takes in theinitializeValues
generated by a Statsig Server SDK that supportsClient SDK Bootstrapping
. Normally, client SDKs fetch this value by hitting the/initialize
endpoint -
consequently, there is no
waitForInitialization
orinitializingComponent
as the SDK is initialized and has all of the values immediately when rendered on the server (or on the first render pass on the client).
Note that if the user object changes, the provider will update the user and values via a call to Statsig servers.
Pick a single provider to wrap your app - don't return the StatsigSynchronousProvider
when executing on the server, and swap it out with the StatsigProvider
when rendered on the client (or vice versa). Pick one provider for your use case and only render that
Manual Exposures v1.21.0+
Manually logging exposures can be tricky and may lead to an imbalance in exposure events. For example, only triggering exposures for users in the Test group of an experiment will imbalance the experiment, making it useless.
Added in version 1.21.0, you can now query your gates/experiments without triggering an exposure as well as manually logging your exposures.
- Check Gate
- Get Config
- Get Experiment
- Get Layer
To check a gate without an exposure being logged, call the following.
const { value } = useGateWithExposureLoggingDisabled("a_gate_name");
Later, if you would like to expose this gate, you can call the following.
Statsig.manuallyLogGateExposure("a_gate_name");
To get a dynamic config without an exposure being logged, call the following.
const { config } = useConfigWithExposureLoggingDisabled(
"a_dynamic_config_name"
);
Later, if you would like to expose the dynamic config, you can call the following.
Statsig.manuallyLogConfigExposure("a_dynamic_config_name");
To get an experiment without an exposure being logged, call the following.
const { config } = useExperimentWithExposureLoggingDisabled("an_experiment_name");
Later, if you would like to expose the experiment, you can call the following.
Statsig.manuallyLogExperimentExposure("an_experiment_name", false);
To get a layer parameter without an exposure being logged, call the following.
const { layer } = useLayerWithExposureLoggingDisabled("a_layer_name");
const result = layer.getValue("a_parameter_name", "fallback");
Later, if you would like to expose the layer parameter, you can call the following.
Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name");
Testing
At Statsig, we use this jest mock to test our components:
let mockGates: Record<string, boolean> = {};
let mockLayers: Record<string, Layer> = {};
jest.mock('statsig-react', () => {
const DynamicConfig = jest.requireActual('statsig-react')
.DynamicConfig as new (mockName: string) => DynamicConfig;
const StatsigMock = {
useGate: (gateName: string) => {
return {
isLoading: false,
value: mockGates[gateName] ?? false,
};
},
useConfig: () => {
return {};
},
useLayer: (name: string) => {
return { layer: mockLayers[name], isLoading: false };
},
useExperiment: (name: string) => {
return {
isLoading: false,
config: new DynamicConfig(name),
};
},
StatsigProvider: (props: object) => {
return <>
props.children
</>
},
Statsig: {
logEvent: () => {},
checkGate: (gateName: string) => mockGates[gateName] ?? false,
getConfig: () => {
return {
get: (name: string, fallback: any) => fallback,
getValue: (name: string, fallback: any) => fallback,
};
},
getLayer: (layerName: string) => {
return StatsigMock.Layer._create(layerName);
},
},
Layer: {
_create(
_layerName: string,
_layerValue: Record<string, any> = {},
_ruleID = '',
_secondaryExposures: Record<string, string>[] = [],
_allocatedExperimentName = '',
) {
return {
get: function <T>(
_key: string,
defaultValue: T,
_typeGuard?: (value: unknown) => value is T,
): T {
return defaultValue;
},
};
},
},
};
return StatsigMock;
});
If you want to use local overrides, you can create a helper function to make this easier:
import { Statsig, StatsigContext, StatsigProvider } from 'statsig-react'
function StatsigOverrides({children}) {
const statsigContext = useContext(StatsigContext);
useEffect(() => {
// make sure you import this from statsig-react!
Statsig.overrideConfig("a_config", {test_key: "test_value"});
}, [statsigContext.initialized]);
return statsigContext.initialized ? children : null;
}
<StatsigProvider ...>
<StatsigOverrides>
<App />
</StatsigOverrides>
</StatsigProvider>
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments
Which Browsers Supported?
The statsig-react
SDK relies on the statsig-js
SDK and inherits its browser compatibility. For more information, see the statsig-js docs.
How do I silence "Call and wait for initialize() to finish first" logs?
Starting in v1.6.0
, setting the environment variable REACT_APP_STATSIG_SDK_MODE=silent
will swallow the Call and wait for initialize() to finish first
exception. For more information, see the release notes for v1.6.0
Can I write my own StatsigProvider?
If you wish to use the React SDK but customize the initialization logic beyond what the StatsigProvider
offers, you can write your own provider. See the above warning on using the global Statsig
singleton before proceeding.
An example provider with custom initialization logic might look something like this:
Reference
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.
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
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
.
Due to the above limitation, the main use case for using the singleton Statsig
class is typically event logging.
static logEvent(eventName: string, value: string | number | null = null, metadata: Record<string, string> | null = null): void
Logs a custom event with optional value and metadata. Note that prior to v1.38.0, this method could throw if you did not specify to waitForInitialization
or waitForCache
if the method was called prior to the sdk initialization (which would happen on the first render path). To avoid this, you should check the const { initStarted } = useContext(StatsigContext);
field of the StatsigContext
and only log events after initStarted
is true.
Parameters:
eventName
: The name of the event to log.
value
: An optional value associated with the event.
metadata
: Optional metadata for the event as a record of key-value pairs.
static checkGate(gateName: string, ignoreOverrides = false): boolean
Checks the status of a feature gate for the current user.
Parameters:
gateName
: The name of the feature gate to check.
ignoreOverrides
: Whether to ignore any local overrides for this gate.
Returns: true if the gate is open for the user, false otherwise.
static getConfig(configName: string, ignoreOverrides = false): DynamicConfig
Retrieves a dynamic configuration by name.
Parameters:
configName
: The name of the dynamic config to retrieve.
ignoreOverrides
: Whether to ignore any local overrides for this config.
Returns: A DynamicConfig
object representing the retrieved configuration.
static getExperiment(experimentName: string, keepDeviceValue = false, ignoreOverrides = false): DynamicConfig
Retrieves an experiment configuration by name.
Parameters:
experimentName
: The name of the experiment to retrieve.
keepDeviceValue
: optional. Whether to keep the value constant for the device, even as the user may fall out of targeting criteria or allocation percentages
ignoreOverrides
: Whether to ignore any local overrides for this experiment.
StatsigProvider
The 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 componentssdkKey: string
- A client SDK key from the Statsig Consoleuser: StatsigUser
- A StatsigUser object. Changing this will update the experiment and gate values, causing a re-initialization and rerenderoptions?: StatsigOptions
- See StatsigOptions. An optional bag of initialization properties (mostly shared with the statsig-js sdk) for advanced configuration.waitForInitialization?: boolean
-initializingComponent?: React.ReactNode | React.ReactNode[]
- A loading component to render if and only ifwaitForInitialization
is set totrue
and the SDK is initializingmountKey?: 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
StatsigSynchronousProvider
The StatsigSynchronousProvider is a altered version of the StatsigProvider
, made specifically for Server Side Rendering but can
also be leveraged for apps that do not require loading states.
children: React.ReactNode | React.ReactNode[]
- One or more child componentssdkKey: string
- A client SDK key from the Statsig Consoleuser: StatsigUser
- A StatsigUser object. Changing this will update the experiment and gate values, causing a re-initialization and rerenderoptions?: StatsigOptions
- See StatsigOptions. An optional bag of initialization properties (mostly shared with the statsig-js sdk) for advanced configuration.initializeValues: Record<string, unknown>
- JSON object, generated by a Statsig Server SDK. See Server Side Rendering.
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 SDKstatsigPromise: React.MutableRefObject<Promise<void>> | null;
a reference to a promise which resolves once SDK initialization is completeinitStarted: boolean
whether the singletonStatsig
has hadinitialize
called on it, meaning the SDK is now usable and can serve checks from cache and queue log eventsuserVersion: number
used internally by the SDK to memoize SDK functions based on the user. Increments when the user object is changed and updateUser is called.
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 (If supported) and cache.Note: Since no network requests will be made, a dummy SDK key starting with "client-" can be used. (eg
"client-key"
)
-
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 (If supported) 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.
- This option configures the maximum time (in milliseconds) the SDK would wait for the network request made by
- 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 forlogEvent
to log event data. Theapi
option controls the evaluation endpoint, andeventLoggingApi
controls the event logging endpoint.
- The SDK will hit different endpoints for
- 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.
- An array of additional StatsigUser objects to be fetched during the
- fetchMode?
network-only | cache-or-network
, defaultnetwork-only
- Changes the behavior of updateUser calls. See Fetch Mode for more details.
- initCompletionCallback?
(initDurationMs: number, success: boolean, message: string | null) => void
, default null- A callback that's invoked whenever initialization has completed.
- updateUserCompletionCallback?
(durationMs: number, success: boolean, message: string | null) => void
, default null- A callback that's invoked whenever an updateUser call has completed.
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 SDKvalue: 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 SDKconfig: DynamicConfig
- the backingDynamicConfig
(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 SDKconfig: DynamicConfig
- the backingDynamicConfig
(see the statsig-js sdk docs for more information)
useLayer
A react hook to get a Statsig Experiment, represented as a Layer.
Parameters:
experimentName: string
- the name of the experiment to get
Returns LayerResult
:
isLoading: boolean;
- the loading/initializing state of the SDKlayer: Layer
- the backingLayer
(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:
eventName: string
value?: string | number | null
metadata?: Record<string, string> | null
usePrefetchUsers
(v1.15.0+)
A react hook to prefetch an array of StatsigUser objects. This will call the underling prefetchUsers method.
Parameters:
users: StatsigUser[]
StatsigContext
export interface TStatsigContext {
initialized: boolean; // whether the Statsig singleton is now initialized
statsigPromise: React.MutableRefObject<Promise<void>> | null; // a reference to the initialization promise for Statsig
userVersion: number; // a counter for the version of the user object used for memoizing values to the StatsigUser
initStarted: boolean; // whether initialization has started (and therefore SDK methods on the Statsig singleton can be called without throwing)
updateUser: UpdateUserFunc; // A method to consume and call in child components to refetch values for a new StatsigUser object
initValuesTime: string | null; // The time field on the initializeValues - for bootstrapping or the StatsigSynchronousProvider only
}