React Native Client SDK
To get started with Statsig in ReactNative, you should use the new Statsig ReactNative SDK
.
This version of the SDK is deprecated and will only receive major bug fixes going forward.
If you already use this deprecated version, you should check out the migration docs.
If you are using Expo, check out our Expo SDK.
This SDK (statsig-react-native
) wraps the statsig-react SDK. It contains the same React Context, Providers, and Hooks, used in the same way, HOWEVER you must import from the statsig-react-native
package.
Installation
You can install the SDK via npm or yarn. In your project directory, run:
- NPM
- Yarn
npm install statsig-react-native
yarn add statsig-react-native
Next, let's install the dependencies we need for the SDK to work:
- NPM
- Yarn
npm install @react-native-async-storage/async-storage react-native-device-info react-native-get-random-values
yarn add @react-native-async-storage/async-storage react-native-device-info react-native-get-random-values
Lastly, if you are on a Mac and developing for iOS, you need to install the pods to complete the linking:
npx pod-install ios # or pod install, in your /ios folder
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-native";
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
statsig-react-native
utilizes React Hooks to provide access to your gates/configs/experiments.
It also exposes a global Statsig
class that you can import outside your
component tree to access this information.
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
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.
- Via Hook
- Directly
import { useGate } from "statsig-react-native";
...
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>;
}
You can call Statsig.checkGate
directly. This can be helpful when gate checks are needed in loops.
Ensure you have set waitForInitialization to true or you may get default values.
import { Statsig } from "statsig-react-native";
...
function MyComponent() {
return (
<div>
{someArray.map((item) => {
if (Statsig.checkGate("a_gate_name")) {
return <div>Passes Gate</div>;
}
return <div>Fails Gate</div>;
})}
</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-native";
...
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-native";
...
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-native";
...
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-native';
...
export default function MyComponent(): JSX.Element {
return <Button
onClick={() => {
Statsig.logEvent("add_to_cart", "SKU_12345", {
price: "9.99",
item_name: "diet_coke_48_pack",
});
}}
/>;
}
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.
setUser({ userID: "another-user" });
There also exists am updateUser
method on the Statsig interface, but calling this directly may lead to issues with the StatsigProvider.
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments
Which Browsers Supported?
The statsig-react-native
SDK relies on the statsig-js
SDK and inherits its browser compatibility. For more information, see the statsig-js docs.
Why a I seeing an "unexpected exception"?
Some users of the ReactNative SDK have reported issues that look like the following:
ERROR [Statsig] An unexpected exception occurred. [TypeError: undefined is not a function (near '...}).finally(function () {...')]
Some libraries, like storybook, remove the finally()
handler for promises. In order to pollyfill this and get around the error, see this thread:
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-native
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
.