React Client SDK for Statsig
info
These docs are for using our react SDK in a single-user, client side context. For react native mobile clients, try our react native sdk
Background
The Statsig React SDK builds on top of the React Context and Hooks APIs, which are only supported in React v16.8.0+. If this requirement prevents you from using the SDK, please let us know.
If you are unfamiliar with using React Hooks, be sure to read the rules of hooks.
Also note that this SDK wraps the statsig-js sdk, and reuses a number of concepts introduced in that SDK. This includes:
- initialization options have the same set of parameters, with additional react-specific parameters.
- hooks for DynamicConfigs return the same
DynamicConfig
object - the
Statsig
singleton mirrors thestatsig-js
sdk
Refer to the statsig-js documentation for more information.
Installing the SDK
You can install the statsig SDK via npm or yarn.
- NPM
- Yarn
npm install statsig-react
yarn add statsig-react
v1.0.0 Update
Migrates the statsig-react
sdk to v4.0 of the statsig-js
SDK. This introduces a number of breaking changes and enhancements.
Breaking Changes:
- Removed the
useStatsig
hook. Instead, useimport Statsig from 'statsig-react'
to use thestatsig-js
sdk for event logging, or gate checks/event logging outside of a component tree. NOTE: SDK methods likecheckGate
andlogEvent
will throw if called beforeinitialize()
- to avoid errors in your component tree, checkinitStarted
from theStatsigContext
, or globally, checkStatsig.initializedCalled()
- Removed the separate
DynamicConfig
type, instead directly exporting the same type from thestatsig-js
sdk.
Enhancements and Bug Fixes:
- Unify the type of
DynamicConfig
to be a single type across this SDK and thestatsig-js
sdk. - Memoizes the result of gate/config checks for a given user for enhanced performance and to reduce duplicate exposures.
- Adds
initializationComponent
to render while initializing ifwaitForInitialization
istrue
- Fetches cached flag values from local storage while initialize is pending if
waitForInitialization
isfalse
- Fixes an issue where changing the user object could trigger an
updateUser
while the SDK was initializing, which would throw an exception
Additional features (inherited from statsig-js
). See the releases for more details:
DynamicConfig
overrides- Ability to
checkGate
andgetConfig
without overrides - Improved support for browsers + event logging, SSR logging bug fix, and configurations for event batch sizes and event flush intervals.
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
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
.
Usage
How we at Statsig use the SDK, and suggested usage.
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';
...
<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';
...
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';
...
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
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 componentssdkKey: string;
- A client SDK key from the Statsig Consoleuser: StatsigUser;
- A Statsig User object. Changing this will update the user and Gate values, causing a re-initializationoptions?: 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 componentsinitializingComponent?: React.ReactNode | React.ReactNode[];
- A loading component to render iff waitForInitialization is set to true and the SDK is initializing
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 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 DynamicConfig.
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: 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 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 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
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
.
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 thestasig-node
server SDK methodgetClientInitializeValues
introduced inv4.13.0
of thestatsig-node
sdk (release notes). - 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.
Custom Initialization
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:
Feel free to reach out to us in the Statsig Slack channel if you are having difficulty setting this up!
Silencing "Call and wait for initialize() to finish first"
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
Testing
Internally at Statsig, we use this jest mock to test our components:
let mockGates: Record<string, boolean> = {};
jest.mock('statsig-react', () => {
return {
useGate: (gateName: string) => {
return {
isLoading: false,
value: mockGates[gateName] ?? false,
};
},
useConfig: () => {
return {};
},
useExperiment: () => {},
Statsig: {
logEvent: () => {},
checkGate: (gateName: string) => mockGates[gateName] ?? false,
getConfig: () => {
return {
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-return */
get: (name: string, fallback: any) => fallback,
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-return */
getValue: (name: string, fallback: any) => fallback,
};
},
},
};
Browser Support
The statsig-react
SDK relies on the statsig-js
SDK and inherits its browser compatibility. For more information, see the statsig-js docs.