Skip to content
Optima docs
SDKsReact Native SDK

Installation

React Native SDK v1.2.0 — Installation

Requirements

  • React Native ≥ 0.76, React ≥ 18.2. The SDK is pure TypeScript — no native module of its own, no autolinking step, no pod install for the SDK itself. It ships as ESM (lib/module), CommonJS (lib/commonjs) and .d.ts (lib/typescript) via react-native-builder-bob, plus a react-native field pointing at src/ so Metro consumes source directly in a monorepo.
  • One required peer: @react-native-async-storage/async-storage (≥ 1.21.0; 1.x, 2.x and 3.x all work) — the default persistence port. Everything else is optional.
  • No fetch polyfill, no JSON library, no UUID library: the SDK uses the global fetch and JSON. For ids it uses crypto.randomUUID/crypto.getRandomValues when the runtime has them, else the optional expo-crypto peer. A bare React Native app with neither should import "react-native-get-random-values"; before importing the SDK — otherwise ids fall back to Math.random and Optima.init logs a warning. The device id doubles as the handle for personalized content, so treat that warning as a fix-before-release.

Install

bun add @optima/react-native @react-native-async-storage/async-storage
# npm install @optima/react-native @react-native-async-storage/async-storage
# yarn add @optima/react-native @react-native-async-storage/async-storage

Expo (managed workflow)

npx expo install @react-native-async-storage/async-storage react-native-webview expo-application expo-localization

expo install resolves each package to the version your Expo SDK expects. Everything past @react-native-async-storage/async-storage here is optional — see Optional peers below for what each one unlocks and what the SDK falls back to without it.

Bare React Native

bun add @optima/react-native @react-native-async-storage/async-storage react-native-webview
cd ios && pod install

pod install is only needed if you added react-native-webview (or any other native peer) — the SDK's own package has no native code, so it never adds a pod itself. On Android, autolinking picks up whatever native peers you installed the normal way; there is nothing SDK-specific to configure in android/.

Optional peers

PeerUnlocksWithout it
react-native-webview (≥ 13.0.0)Rendering unstructured (raw HTML/CSS/JS) content items in an isolated WebView — see chapter 5.display.htmlMode silently degrades from "webview" to "off" at Optima.init time, with one logger.warn ("react-native-webview is not installed; unstructured HTML items will surface as content:item events (htmlMode=off)"). Every other content type is unaffected.
expo-applicationReading the app's bundle/package id and version (applicationId/nativeApplicationVersion) for context.url and the tracking ua string.Falls through to react-native-device-info, then to config.app (see chapter 2), then to "unknown"/"unknown" with one warning.
react-native-device-infoSame as above, as a fallback when expo-application isn't installed (a bare-RN-friendly alternative).Same fallback chain as above.
expo-localizationReading the device's locale tag for context.language on every hit, OptimaClient.language, and the built-in consent banner's language ladder (see chapter 4).context.language and OptimaClient.language default to "en".

None of these are required for the SDK to function — Optima.init never throws because an optional peer is missing; it degrades the one feature that peer enables and logs once. config.app (explicit {id, version} in OptimaConfig) always wins over any of the auto-detection peers, so you can skip expo-application/react-native-device-info entirely if you're willing to pass those two strings yourself.

Optional-peer detection relies on Metro's allowOptionalDependencies, which is on by default in both @react-native/metro-config and expo/metro-config — if your metro.config.js turns it off, a missing optional peer becomes a bundle-time error instead of a graceful fallback.

Initializing the SDK

Call Optima.init once, as early as possible. Unlike the Android/iOS SDKs, Optima.init is asynchronous — it hydrates persisted state (device id, consent, the outbox, …) from AsyncStorage before the runtime is usable. A useEffect in your app's root component is a common place to call it (shown below); see Calling before init resolves further down for why calling it even earlier, at module scope, is often better — and for what happens to calls made in the meantime either way:

// App.tsx
import { useEffect } from "react";
import { Optima } from "@optima/react-native";
import { OptimaHost } from "@optima/react-native/ui";

export default function App() {
  useEffect(() => {
    void Optima.init({
      key: "oek_shop_a1b2c3",
      endpoint: "https://edge.shop.example",
      debug: __DEV__,
    });
  }, []);

  return (
    <YourProviders>
      <YourNavigator />
      <OptimaHost />
    </YourProviders>
  );
}

You do not need to await the returned promise before using Optima.instance — see Calling before init resolves below. key and endpoint come from your Optima console: Edge → SDK keys, where you create (or reuse) a key on the mobile platform — see chapter 2 for what that platform distinction controls server-side.

Expo Router

Initialize in the root layout instead of a plain App.tsx:

// app/_layout.tsx
import { useEffect } from "react";
import { Stack } from "expo-router";
import { Optima } from "@optima/react-native";
import { OptimaHost } from "@optima/react-native/ui";

export default function RootLayout() {
  useEffect(() => {
    void Optima.init({ key: "oek_shop_a1b2c3", endpoint: "https://edge.shop.example", debug: __DEV__ });
  }, []);

  return (
    <>
      <Stack />
      <OptimaHost />
    </>
  );
}

Calling before init resolves

Optima.instance is one stable object for the process — before, during, and after init, it's the same facade, so a hook or a module-level const optima = Optima.instance never has to guard against "has init run yet." What happens to a call made on it depends on exactly one of four states:

StateMutating calls (track, identify, consent.set, reset, flush, push.setToken, …)Read-only accessors (deviceId, consent.get(), isReady)
idle — Optima.init has not been called yetQueued, in the order called, capped at 100 entries — beyond that, the oldest queued call is dropped and one warning logs. Replayed against the real runtime, in order, once init resolves.Safe fallbacks ("", an empty ConsentState, false).
initializing — an init call is in flight (hydrating)Same as idle: queued and replayed in order once init resolves.Same safe fallbacks as idle.
ready — init resolved successfullyRun immediately against the real runtime.Real values.
failed — init was called and threw during construction (a bad config, an unexpected exception — not a Storage port failure, which degrades to in-memory storage and still succeeds, see chapter 9)Dropped — this is the only state in which a call is genuinely lost rather than queued. Exactly one warning logs across every dropped call, however many there are ("Optima used without an initialized SDK; calls are no-ops").Same safe fallbacks as idle.

content.slot(name) follows the same idle/initializing-safe pattern by a different mechanism: it hands back a handle that starts empty and binds to the real slot the moment the runtime is ready — a component that calls useSlot (or mounts OptimaSlot/OptimaHost) before Optima.init has finished is safe and simply renders nothing until content arrives, in every state including failed. Nothing ever throws into your app, in any state.

Because idle queues exactly like initializing, it does not matter that React runs a child component's effects before its parent's — a child's useScreenTracking/track firing before the root's useEffect(() => Optima.init(...)) has even run queues normally and lands, in order, once init resolves.

Recommended: call Optima.init as early as possible — ideally at module scope in your app's entry file, outside any component, so it starts before the first component even renders:

// index.js (or the very top of App.tsx, outside the component function)
import { Optima } from "@optima/react-native";

void Optima.init({ key: "oek_shop_a1b2c3", endpoint: "https://edge.shop.example", debug: __DEV__ });

The useEffect form shown above works too — the idle queue exists precisely so it does — but a module-scope call means fewer calls ever need to queue at all, and it isn't gated on a first render + effect flush before starting hydration.

A second call to Optima.init (from either form) is a no-op with a "Optima.init called twice; the first configuration stays" warning — the first configuration always wins.

Placing <OptimaHost />

Put exactly one <OptimaHost /> near the root of your app, inside any theme/navigation providers but outside (or alongside) your navigator — it renders every overlay-placement content presentation from every slot you've ever declared (plus the built-in consent banner) in an absolute-fill, pointerEvents="box-none" layer, so it composes predictably with your own modals and navigators instead of fighting them. It renders null when there's nothing to show — there is no cost to leaving it mounted on every screen. See chapter 5 for what it draws and chapter 4 for the consent banner it hosts.

The SDK has no router dependency and does not track screens automatically — you call screen(name) yourself, or wire one of these two router-agnostic helpers:

React Navigation — three lines on your NavigationContainer:

import { useRef } from "react";
import { NavigationContainer, type NavigationContainerRef } from "@react-navigation/native";
import { Optima } from "@optima/react-native";

function App() {
  const ref = useRef<NavigationContainerRef<any>>(null);
  return (
    <NavigationContainer
      ref={ref}
      onReady={() => Optima.instance.navigation.onReady(ref.current?.getRootState())}
      onStateChange={(state) => Optima.instance.navigation.onStateChange(state)}
    >
      {/* ... */}
    </NavigationContainer>
  );
}

Expo Router — useScreenTracking from ./ui, given the current pathname:

// app/_layout.tsx (inside a component that has route context)
import { usePathname } from "expo-router";
import { useScreenTracking } from "@optima/react-native/ui";

function ScreenTracker() {
  useScreenTracking(usePathname());
  return null;
}

Both approaches end up calling screen(name) for you, which is track("screen_view", name, ...) plus attribution enrichment and a re-fetch of every declared content slot — see chapter 3 for the exact behaviour.

Operator prerequisites

None of these are code changes — they're one-time console/config steps an operator performs per tenant before traffic from this SDK is fully useful:

  • An SDK key on the mobile platform (Console → Edge → SDK keys). A web-platform key will often still authenticate, but content targeting and tracking-entity resolution are platform-scoped server-side, so a mismatched platform produces confusing gaps rather than a clean error — see chapter 2.

  • A screen_view category mapping (Console → category mappings) — without it, every screen() call is dropped server-side as unknown_category. The recommended mapping:

    Source fieldMaps to
    $context.urlurl (the app://<appId>/<screen> convention — chapter 5)
    $context.titlescreen name
    $props.session_idsession id
    $props.session_startsession-start marker
    utm_source/utm_medium/utm_campaign/utm_term/utm_content/gclid/fbclidattribution props
  • push_token_fcm and/or push_token_apns in identify_allowed_keys — otherwise push.setToken's identify call succeeds locally but the server drops the identifier, and a campaign never actually reaches the device. See chapter 7.

  • EMAIL_TRACK_KEY configured, and open tracking on for the push template — required for push.trackOpen to have anything to record; see chapter 7.

First hit checklist

  1. Optima.init({...}) called once, in your root component, with debug: true while you verify.
  2. Watch your Metro/device logs for the [optima] prefix (see Verifying the install below).
  3. Call Optima.instance.track("app_open") (or just navigate — if navigation wiring is in place, a screen_view fires on its own).
  4. Confirm the screen_view category mapping exists in the console — an unmapped category is silently dropped server-side (see chapter 9).
  5. Look for a track event (Optima.instance.on("track", (p) => console.log(p))) or a 200 server response in your debug log — either confirms the batch landed.

Verifying the install

Set debug: true in your config. Every enqueue, flush, server response, dropped item, and internal error logs a line prefixed [optima] via console.log/console.warn (the default ConsoleLogger). A 401/403 on the first flush almost always means the key is for the wrong platform or has been revoked — see chapter 9. Once you see the track event fire (or a 2xx line in your log for POST /edge/v1/track), the install is complete and hits are landing.

Other known gaps and parked items are tracked in the SDK repository's TODO.md.

On this page