Examples

A complete React Native start sequence with the SDK, the tracer provider and React Navigation, followed by a traced API call, a custom span, handled errors, an error boundary and a logout flow.

The examples build one small app: a shared sophonz.ts module, an App.tsx that starts everything in order, and the patterns that use it. They assume a bare React Native app with React Navigation; the Navigation page shows the same start sequence in an expo-router layout.

Packages

npm install @sophonz/react-native@0.1.0 \
  @sophonz/react-native-tracer-provider@0.1.0 \
  @sophonz/react-native-navigation@0.1.0 \
  @opentelemetry/api \
  @react-navigation/native @react-navigation/native-stack
cd ios && pod install

The native setup from Installation is assumed: sophonz-config.json on Android, and on iOS either the options below or a native start.

The shared module

One place for the configuration and the tracer, so screens do not import the provider.

src/sophonz.ts
import {trace} from "@opentelemetry/api";
import type {SDKConfig} from "@sophonz/react-native";
 
// Stable identities: the hooks re-run when these objects change
export const SOPHONZ_CONFIG: SDKConfig = {
  ios: {
    collectorUrl: "https://in.sophonz.ai",
    appKey: "sk_ios_replace_me",
    appName: "shop-ios",
    project: "shop",
    deploymentEnvironment: __DEV__ ? "development" : "production",
    disabledUrlPatterns: ["analytics.example.com"],
  },
  trackUnhandledRejections: true,
};
 
export const TRACER_CONFIG = {setGlobalContextManager: true};
 
// Resolves to the Sophonz provider once App registers it; a no-op tracer before that
export const tracer = () => trace.getTracer("shop", "1.4.0");

Start sequence

App.tsx starts the SDK, creates the tracer provider when the SDK is running, registers it globally, and only then renders the navigation tree, so the first screen span is not lost.

App.tsx
import {useEffect, useRef} from "react";
import {ActivityIndicator, View} from "react-native";
import {trace} from "@opentelemetry/api";
import {NavigationContainer, useNavigationContainerRef} from "@react-navigation/native";
import {createNativeStackNavigator} from "@react-navigation/native-stack";
import {configureSDKErrorLogging, useSophonz} from "@sophonz/react-native";
import {useSophonzNativeTracerProvider} from "@sophonz/react-native-tracer-provider";
import {SophonzNavigationTracker} from "@sophonz/react-native-navigation";
 
import {SOPHONZ_CONFIG, TRACER_CONFIG} from "./src/sophonz";
import {ErrorBoundary} from "./src/ErrorBoundary";
import {OrdersScreen} from "./src/screens/OrdersScreen";
import {OrderDetailScreen} from "./src/screens/OrderDetailScreen";
 
configureSDKErrorLogging({enabled: __DEV__, allowLogToConsole: true});
 
const Stack = createNativeStackNavigator();
 
export default function App() {
  // 1. Start the SDK (or attach to a native start) and install the JS error handlers
  const {isPending, isStarted} = useSophonz(SOPHONZ_CONFIG);
 
  // 2. Create the tracer provider once the SDK is running
  const {tracerProvider} = useSophonzNativeTracerProvider(TRACER_CONFIG, isStarted);
 
  // 3. Make it the global provider so trace.getTracer() reaches it
  useEffect(() => {
    if (tracerProvider) {
      trace.setGlobalTracerProvider(tracerProvider);
    }
  }, [tracerProvider]);
 
  const navigation = useNavigationContainerRef();
  const trackerRef = useRef(navigation);
 
  if (isPending || (isStarted && !tracerProvider)) {
    return (
      <View style={{flex: 1, justifyContent: "center"}}>
        <ActivityIndicator />
      </View>
    );
  }
 
  // If the SDK failed to start, the app still runs without telemetry
  return (
    <ErrorBoundary>
      <NavigationContainer ref={navigation}>
        <SophonzNavigationTracker
          ref={trackerRef}
          tracerProvider={tracerProvider ?? undefined}
          debug={__DEV__}>
          <Stack.Navigator>
            <Stack.Screen name="Orders" component={OrdersScreen} />
            <Stack.Screen name="OrderDetail" component={OrderDetailScreen} />
          </Stack.Navigator>
        </SophonzNavigationTracker>
      </NavigationContainer>
    </ErrorBoundary>
  );
}

What each step records:

StepTelemetry
useSophonzUnhandled JS exceptions, unhandled promise rejections, React Native and SDK versions. Native capture was already running if the SDK started natively
useSophonzNativeTracerProviderNothing by itself; spans created through it
SophonzNavigationTrackerA ux.view span named Orders, then OrderDetail, and so on

A traced API call

A custom span around the whole operation, with its ids sent as traceparent, so the backend's spans nest under it. The native SDK still records the request itself as a network span.

src/api/orders.ts
import {isSpanContextValid, SpanStatusCode} from "@opentelemetry/api";
import type {SophonzNativeSpan} from "@sophonz/react-native-tracer-provider";
 
import {tracer} from "../sophonz";
 
export type Order = {id: string; total: number};
 
export async function fetchOrders(): Promise<Order[]> {
  const span = tracer().startSpan("fetch-orders", {attributes: {"spz.type": "perf"}});
 
  try {
    // a Sophonz span gets its ids from the native side; wait for them
    const ctx =
      "spanContextAsync" in span
        ? await (span as SophonzNativeSpan).spanContextAsync()
        : span.spanContext();
 
    const response = await fetch("https://api.example.com/v1/orders", {
      headers: isSpanContextValid(ctx) ? {traceparent: `00-${ctx.traceId}-${ctx.spanId}-01`} : {},
    });
    span.setAttribute("http.response.status_code", response.status);
 
    if (!response.ok) {
      throw new Error(`orders request failed with ${response.status}`);
    }
 
    const orders: Order[] = await response.json();
    span.setAttribute("orders.count", orders.length);
    return orders;
  } catch (e) {
    span.recordException(e as Error);
    span.setStatus({code: SpanStatusCode.ERROR});
    throw e;
  } finally {
    span.end();
  }
}

Before the provider is registered, trace.getTracer hands out a no-op tracer whose spans have no spanContextAsync and an all-zero context; the checks above then send no header rather than an invalid one. In the start sequence above, screens render only after registration.

Because the header is set by hand, it is sent on both platforms regardless of the native injection settings, and neither SDK replaces it. See Networking.

A custom span with children

Measure a multi-step operation, keeping the parent explicit across await.

src/checkout.ts
import {asParent, endAsFailed} from "@sophonz/react-native-tracer-provider";
 
import {tracer} from "./sophonz";
 
export async function checkout(cartId: string) {
  const t = tracer();
  const root = t.startSpan("checkout", {attributes: {"cart.id": cartId}});
 
  try {
    const validate = t.startSpan("validate-cart", {}, asParent(root));
    await validateCart(cartId);
    validate.end();
 
    const pay = t.startSpan("charge-card", {}, asParent(root));
    try {
      await chargeCard(cartId);
      pay.end();
    } catch (e) {
      endAsFailed(pay);
      throw e;
    }
 
    root.end();
  } catch (e) {
    endAsFailed(root);
    throw e;
  }
}

Handled errors and breadcrumbs

src/screens/OrdersScreen.tsx
import {useCallback, useEffect, useState} from "react";
import {Button, FlatList, Text, View} from "react-native";
import {addBreadcrumb, logHandledError} from "@sophonz/react-native";
 
import {fetchOrders, type Order} from "../api/orders";
 
export function OrdersScreen() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [failed, setFailed] = useState(false);
 
  const load = useCallback(async () => {
    addBreadcrumb("orders: load requested");
    try {
      setOrders(await fetchOrders());
      setFailed(false);
    } catch (e) {
      // the user sees a retry button; we still want to know it happened
      logHandledError(e as Error, {screen: "Orders"});
      setFailed(true);
    }
  }, []);
 
  useEffect(() => {
    load();
  }, [load]);
 
  return (
    <View>
      {failed && <Button title="Retry" onPress={load} />}
      <FlatList data={orders} keyExtractor={o => o.id} renderItem={({item}) => <Text>{item.id}</Text>} />
    </View>
  );
}

Property values must be strings; on iOS a number makes the call resolve false.

Error boundary

Errors caught by an error boundary never reach the global handler, so record them here.

src/ErrorBoundary.tsx
import React from "react";
import {Text} from "react-native";
import {logHandledError, logIfComponentError} from "@sophonz/react-native";
 
type Props = {children: React.ReactNode};
 
export class ErrorBoundary extends React.Component<Props, {failed: boolean}> {
  state = {failed: false};
 
  static getDerivedStateFromError() {
    return {failed: true};
  }
 
  componentDidCatch(error: Error, info: React.ErrorInfo) {
    logHandledError(error, {boundary: "root"});
    logIfComponentError(Object.assign(error, {componentStack: info.componentStack ?? ""}));
  }
 
  render() {
    return this.state.failed ? <Text>Something went wrong.</Text> : this.props.children;
  }
}

Login and logout

src/auth.ts
import {
  addSessionProperty,
  clearAllUserPersonas,
  clearUserIdentifier,
  endSession,
  setUserIdentifier,
  addUserPersona,
} from "@sophonz/react-native";
 
export async function onLogin(user: {id: string; plan: "free" | "pro"}) {
  await setUserIdentifier(user.id); // an internal id, not an email
  await addUserPersona(user.plan);
  await addSessionProperty("login_method", "password", false);
}
 
export async function onLogout() {
  await clearUserIdentifier();
  await clearAllUserPersonas();
  await endSession(); // the next user's activity starts in a fresh session
}

TIP — This is just the beginning

Now ship your app. Sophonz surfaces the problems real users hit — so your app evolves on its own.