React Native
Screens, events, identify, revenue, flags and an offline queue for React Native apps.
@stancelens/react-native works in bare React Native and in Expo. It has no native code of its own: every native module it reads is an optional peer, so nothing breaks when one is missing. Read Mobile apps for how sessions, screens and offline delivery work across the mobile SDKs.
The package isn't on npm yet. Build it from packages/react-native in the Stancelens repository (bun install && bun run build) and install that folder, or an npm pack tarball of it, in your app.
Install
npm install @stancelens/react-native @react-native-async-storage/async-storage
# optional: app version, device model and device type
npm install react-native-device-info
cd ios && pod installOnly @stancelens/react-native is required. Without AsyncStorage (or another storage), the install ID and the offline queue live in memory and reset on every app start; development builds log a warning when that happens. Using Expo? See Expo.
Set up
import { StancelensProvider } from "@stancelens/react-native";
export default function App() {
return (
<StancelensProvider site="SITE_ID" host="https://stancelens.com">
<RootNavigator />
</StancelensProvider>
);
}site and host are both required. Calling init() again with the same site and host returns the same client, so fast refresh doesn't create duplicates. Calls made before init() are dropped, with a one-time warning.
Track events
import {
track, screen, identify, reset, revenue, captureException,
flag, getFlag, optOut, optIn, flush,
} from "@stancelens/react-native";
track("signup_started", { plan: "pro" }); // custom event
screen("Settings/Profile", { tab: "general" }); // page view with path "/Settings/Profile"
identify("user_123", { plan: "pro" }); // later events carry the user ID
reset(); // log out: new anonymous ID and session
revenue(19.99, "EUR", { sku: "pro" }); // event "purchase" with revenue
revenue(5, "USD", undefined, "tip"); // custom event name
captureException(error, { screen: "Checkout" }); // $error
await flag("new-checkout"); // false | true | "variant"; records $exposure once (not for unknown keys)
getFlag("new-checkout"); // cached value, undefined until loaded; no exposure
optOut();
optIn(); // remembered across restarts
await flush(); // send the queue nowHooks
import { useStancelens, useFlag } from "@stancelens/react-native";
function Checkout() {
const variant = useFlag("new-checkout"); // undefined while loading; records $exposure once
const stancelens = useStancelens(); // the client: stancelens.track(...), stancelens.getSessionId()
return variant === "test" ? <NewCheckout /> : <OldCheckout />;
}Hooks work inside <StancelensProvider>, or anywhere after init().
Screen tracking
A screen view is a page view with path "/" + screen name and the name as title. When the screen changes or the app goes to the background, the time spent on it (background time excluded) is sent as engagement if it was at least one second. Events tracked while a screen is open carry its path.
React Navigation
import { NavigationContainer, useNavigationContainerRef } from "@react-navigation/native";
import { useStancelensNavigationTracking } from "@stancelens/react-native";
function Navigation() {
const navigationRef = useNavigationContainerRef();
useStancelensNavigationTracking(navigationRef);
return <NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>;
}The focused route's name becomes the screen name, sent once per route; param changes on the same route aren't counted again, and route params aren't sent. To rename, skip or add properties:
useStancelensNavigationTracking(navigationRef, {
routeToName: (route) => (route.name === "Debug" ? null : route.name),
routeToProps: (route) => (route.name === "Product" ? { category: "shoes" } : undefined),
});It accepts useNavigationContainerRef(), createNavigationContainerRef() or a useRef passed to NavigationContainer. For Expo Router, see Expo.
Options
| Option | Default | |
|---|---|---|
site | required | Site ID |
host | required | Your Stancelens server, e.g. https://stancelens.com |
storage | AsyncStorage if installed, else memory | Any { getItem, setItem, removeItem }, sync or async |
context | detected | Override detected fields, e.g. { app_version: "1.2.0 (45)" } |
flushAt | 20 | Send when this many events are queued |
flushInterval | 10000 | Otherwise send at most this often (ms) |
maxBatchSize | 50 | Events per request (server limit 100) |
maxQueueSize | 1000 | Oldest events are dropped beyond this |
sessionTimeout | 1800000 | 30 minutes of inactivity starts a new session |
preloadFlags | true | Fetch flags at startup and after identify/reset |
defaultOptOut | false | Start opted out until optIn() |
captureErrors | false | Send uncaught JS errors as $error |
userAgent | built from the device | See User-Agent; false keeps the platform default |
debug | false | Log queueing and sends |
Sessions, queue and delivery
- Install ID: a random ID (
vid) generated on first launch and stored.reset()replaces it. - Sessions: the SDK owns a
session_id. A new one starts after 30 minutes without activity; time in the background counts, so returning after more than 30 minutes starts a new session and re-sends the open screen as its first view. A restart within 30 minutes continues the session. - Queue: every event is saved to storage with the time it happened (
ts). Events queued offline go out on a later flush or the next launch. - Batching: sent when
flushAtevents are queued, everyflushIntervalms, when the app goes to the background, and onflush(). - Retries: network errors, timeouts (15 s), HTTP 408, 429 and 5xx keep the batch and retry with exponential backoff (1 s, 2 s, 4 s… up to 5 minutes, ±25% jitter); a
Retry-Afterheader sets the earliest next attempt. Every event carriessent_atand an event ID, so the server corrects a wrong device clock and drops a repeat. Other 4xx responses mean the server rejected the batch as invalid; it's dropped rather than retried forever.
Storage
import { init, mmkvStorage, secureStoreStorage } from "@stancelens/react-native";
import { MMKV } from "react-native-mmkv";
import * as SecureStore from "expo-secure-store";
init({ site, host, storage: mmkvStorage(new MMKV({ id: "stancelens" })) }); // MMKV v4: createMMKV()
init({ site, host, storage: secureStoreStorage(SecureStore) });expo-secure-store is meant for small secrets, and a large offline queue can exceed what it stores well. Prefer AsyncStorage or MMKV unless you need encryption at rest.
What is collected
| Field | Source |
|---|---|
platform | Always react-native |
sdk | stancelens-react-native/<version> |
os | Platform.OS (iOS, Android; iPadOS with expo-device on iPad) |
os_version | expo-device, react-native-device-info, else Platform |
device_type | expo-device, react-native-device-info, else Platform.isPad/isTV and screen size (shortest side of 600 pt or more is a tablet) |
device_model | expo-device, react-native-device-info, else Platform.constants.Model (Android only) |
app_version | In Expo Go, expoConfig.version (+ build number) from expo-constants; otherwise expo-application, react-native-device-info, then expo-constants; or context.app_version |
language, timezone | expo-localization, else Intl |
screen | Screen size in points from Dimensions, e.g. 393x852 |
vid, session_id, uid | See above (uid only after identify) |
Anything you pass in context overrides the detected value. No advertising IDs, contacts or location.
User-Agent
React Native's default User-Agent (okhttp/… on Android, App/1 CFNetwork/… Darwin/… on iOS) looks like a bot to servers that filter on browser-like user agents. The SDK sends one in the conventional form, built only from the OS, version and model it already sends, e.g. Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) Mobile stancelens-react-native/0.1.0. Set userAgent to your own string, or false to keep the platform default.
Errors
init({ site, host, captureErrors: true });This installs React Native's global JS error handler (ErrorUtils). Uncaught errors are sent as $error with message, stack, type, fatal, source (the current screen path) and app_version, and the previous handler (red box, crash) still runs. For fatal errors the SDK starts a send at once and also writes the event to the queue, but the app may terminate first; the event then arrives on the next launch only if the storage write completed. Unhandled promise rejections and native crashes aren't captured. Call captureException(error) for errors you catch yourself.
Other JavaScript runtimes
@stancelens/react-native/core has no React or React Native imports. It exports StancelensClient, MemoryStorage and the storage adapters, for Node, tests or any runtime with fetch:
import { StancelensClient, MemoryStorage } from "@stancelens/react-native/core";
const client = new StancelensClient({
site: "SITE_ID",
host: "https://stancelens.com",
storage: new MemoryStorage(),
context: { os: "iOS" },
});
client.track("hello");
await client.flush();