Skip to Content
TrichiDataTrichiData

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-localization

Works 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-install

Requires 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

PropTypeDefaultDescription
apiKeystringrequiredProject API key (prj_ak_...)
autoInitbooleantrueCall init() on mount
devicePartial<DeviceInfo>—Override auto-detected device fields
trackingTrackingContext—Optional override (no auto cookie parse on RN; SDK still sends a generated clientId if omitted)
requireConsentbooleanfalseSend 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-install

What 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 to background or inactive. Call await client.flush() to send now.
  • Anonymous id and sessions. A persistent anonymousId and a clientSessionId (new after 30 minutes of inactivity) are attached to every event. Call await client.reset() on logout.
  • Platform. ios or android is detected from Platform.OS and sent on init. The device IP is no longer sent; the server uses the request IP.
  • Consent. requireConsent on the provider (or client) holds back all tracking until await 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` event

Every 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.

FieldExpoBare React NativeFallback
userAgentexpo-constants getWebViewUserAgentAsync(), then expo-devicereact-native-device-info getUserAgent()Platform.OS/Version
localeexpo-localization getLocales()react-native-localize getLocales()Intl
timezoneexpo-localization getCalendars()react-native-localize getTimeZone()Intl
ip0.0.0.00.0.0.00.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

ExportPurpose
TrichiDataProviderContext provider with optional auto-init
useTrichiDataHook to access TrichiDataClient
TrichiDataClientClient for use without the provider
getTrichiDataNavigationHandlersonReady / onStateChange handlers for React Navigation screen tracking

Client methods

MethodDescription
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

On this page