React Native SDK
Install and set up @trichidata/react-native in mobile applications.
Use this guide when your app is built with React Native 0.69+.
For session flow and event schemas, see the REST API. For a guided first integration, see Quickstart.
Installation
@react-native-async-storage/async-storage is a required peer dependency (new in 0.6.0): the SDK imports it directly, so the app does not build without it. Device fields (userAgent, locale, timezone) are read from platform libraries. Install the set that matches your environment — the SDK auto-detects which one is available at runtime.
Expo (Expo Go or development build)
npx expo install @trichidata/react-native @react-native-async-storage/async-storage expo-constants expo-device expo-localizationWorks in Expo Go — the Expo modules ship inside the Expo Go runtime.
Bare React Native
npm install @trichidata/react-native @react-native-async-storage/async-storage react-native-device-info react-native-localize
npx pod-installRequires react >= 18, react-native >= 0.69 and @react-native-async-storage/async-storage >= 1.17 as peer dependencies. The device-info libraries above are optional: install the Expo set for Expo projects, or the bare set otherwise. If neither is installed, the SDK falls back to Platform + Intl.
Setup
Provider
Wrap your application tree with TrichiDataProvider:
import { TrichiDataProvider } from '@trichidata/react-native';
function App() {
return (
<TrichiDataProvider apiKey="prj_ak_xxxxxxxxxxxx">
<RootNavigator />
</TrichiDataProvider>
);
}Props
| Prop | Type | Default | Description |
|---|---|---|---|
apiKey | string | required | Project API key (prj_ak_...) |
autoInit | boolean | true | Call init() on mount |
device | Partial<DeviceInfo> | — | Override auto-detected device fields |
tracking | TrackingContext | — | Optional override (no auto cookie parse on RN; SDK still sends a generated clientId if omitted) |
requireConsent | boolean | false | Send nothing until client.setConsent({ analytics: true }) |
onError | (error) => void | — | Called when a batch is dropped or a background operation fails (see error codes) |
The provider also accepts the other client options (flushAt, flushIntervalMs, sessionTimeoutMs, maxQueueSize (default 500), retryBaseMs, retryMaxMs).
When autoInit is true, the provider calls init_sdk with device info on mount. Device fields are resolved automatically depending on the environment (see Device info sources). The session ID from the response is stored and sent on subsequent requests.
Hook
Use useTrichiData() to access the client anywhere inside the provider:
import { useTrichiData } from '@trichidata/react-native';
function CheckoutButton() {
const client = useTrichiData();
const handlePress = async () => {
await client.checkoutStarted({
total: 99.9,
currency: 'USD',
items: [{ productId: 'p1', name: 'Widget', price: 99.9, quantity: 1 }],
});
};
return <Button title="Checkout" onPress={handlePress} />;
}useTrichiData() returns a TrichiDataClient instance. It throws if used outside TrichiDataProvider.
Manual initialization
Set autoInit={false} when you need to control when init() runs:
<TrichiDataProvider apiKey="prj_ak_xxx" autoInit={false}>
<App />
</TrichiDataProvider>import { useTrichiData } from '@trichidata/react-native';
function App() {
const client = useTrichiData();
useEffect(() => {
void client.init();
}, [client]);
return <RootNavigator />;
}Persistence (new in 0.6.0)
The SDK stores the anonymous id, session and unsent events in AsyncStorage, so they survive app restarts. @react-native-async-storage/async-storage is a required peer dependency: without it the app fails to build. It is included in the install commands above. To add it to an existing app:
# Expo
npx expo install @react-native-async-storage/async-storage
# Bare React Native
npm install @react-native-async-storage/async-storage
npx pod-installWhat is new in 0.6.0
- Queue and retry. Track methods return
{ eventId }immediately. Events are persisted, sent in batches (every 5 s or 20 events) with retry and backoff, and flushed when the app goes tobackgroundorinactive. Callawait client.flush()to send now. - Anonymous id and sessions. A persistent
anonymousIdand aclientSessionId(new after 30 minutes of inactivity) are attached to every event. Callawait client.reset()on logout. - Platform.
iosorandroidis detected fromPlatform.OSand sent on init. The device IP is no longer sent; the server uses the request IP. - Consent.
requireConsenton the provider (or client) holds back all tracking untilawait client.setConsent({ analytics: true }). - Automatic attribution (deep links) is not included yet.
Screen tracking
await client.trackScreen('Checkout', { step: 2 }); // sets the current screen and tracks a `screen` eventEvery later event carries the current screen. With React Navigation, use the helper (no @react-navigation dependency is required):
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import { getTrichiDataNavigationHandlers, useTrichiData } from '@trichidata/react-native';
function Root() {
const client = useTrichiData();
const navigationRef = useNavigationContainerRef();
const nav = useMemo(() => getTrichiDataNavigationHandlers(client), [client]);
return (
<NavigationContainer
ref={navigationRef}
onReady={() => nav.onReady(navigationRef)}
onStateChange={() => nav.onStateChange(navigationRef)}
>
{/* screens */}
</NavigationContainer>
);
}Pass appVersion in identify() from your app config (e.g. Expo expo-application, or your own build metadata).
Device info sources
On init(), the SDK detects the environment and reads device fields from the matching stack. Expo projects use Expo modules only; bare projects use the community libraries.
| Field | Expo | Bare React Native | Fallback |
|---|---|---|---|
userAgent | expo-constants getWebViewUserAgentAsync(), then expo-device | react-native-device-info getUserAgent() | Platform.OS/Version |
locale | expo-localization getLocales() | react-native-localize getLocales() | Intl |
timezone | expo-localization getCalendars() | react-native-localize getTimeZone() | Intl |
ip | 0.0.0.0 | 0.0.0.0 | 0.0.0.0 |
Detection is based on the presence of expo-constants. If the preferred stack is missing or throws, the SDK falls back to Platform + Intl, so init() never crashes.
React Native exports
| Export | Purpose |
|---|---|
TrichiDataProvider | Context provider with optional auto-init |
useTrichiData | Hook to access TrichiDataClient |
TrichiDataClient | Client for use without the provider |
getTrichiDataNavigationHandlers | onReady / onStateChange handlers for React Navigation screen tracking |
Client methods
| Method | Description |
|---|---|
init(params?) | Start a session (init_sdk); device collected under the hood |
trackScreen(name, properties?) | Set the current screen and track a screen event |
flush() | Send queued events now |
shutdown() | Stop timers, then flush once (no retry) |
reset() | Clear identity and start a new anonymous id and session |
setConsent({ analytics }) | Allow or stop tracking (use with requireConsent) |
identify({ userId?, appVersion? }) | Associate session context — at least one field required |
page / productViewed / … | Typed helpers for reserved event names |
trackCustom(name, properties?) | Custom (non-reserved) event |
See REST API for reserved eventName values and properties schemas.
See also
- Quickstart — track your first event
- REST API — event types and property constraints
- React SDK — if you use React on the web