Skip to Content
TrichiDataTrichiData

React SDK

Install and set up @trichidata/react in React applications.

Use this guide when your app is built with React 18+.

For session flow and event schemas, see the REST API. For a guided first integration, see Quickstart.

Installation

npm install @trichidata/react

Requires react >= 18 as a peer dependency.

Setup

Provider

Wrap your application tree with TrichiDataProvider:

import { TrichiDataProvider } from '@trichidata/react';

function App() {
  return (
    <TrichiDataProvider apiKey="prj_ak_xxxxxxxxxxxx">
      <Routes />
    </TrichiDataProvider>
  );
}

Props

PropTypeDefaultDescription
apiKeystringrequiredProject API key (prj_ak_...)
autoInitbooleantrueCall init() on mount
devicePartial<DeviceInfo>—Override auto-detected device fields
trackingTrackingContext—Override auto-parsed GA/Meta cookies
autoPageviewsbooleantrueTrack page on mount and on every SPA navigation. Set false if you already call client.page() per route
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). See Browser SDK options.

When autoInit is true, the provider calls init_sdk with browser device info and tracking (cookies when available, otherwise a generated GA-like clientId) on mount. Session cookies are handled automatically in the browser.

Hook

Use useTrichiData() to access the client anywhere inside the provider:

import { useTrichiData } from '@trichidata/react';

function CheckoutButton() {
  const client = useTrichiData();

  const handleClick = async () => {
    await client.checkoutStarted({
      total: 99.9,
      currency: 'USD',
      items: [{ productId: 'p1', name: 'Widget', price: 99.9, quantity: 1 }],
    });
  };

  return <button onClick={handleClick}>Checkout</button>;
}

useTrichiData() returns a TrichiDataClient instance. It throws if used outside TrichiDataProvider.

What is new in 0.6.0

  • Queue and retry. Track methods return { eventId } immediately. Events are persisted in localStorage (in memory when it is unavailable), sent in batches (every 5 s or 20 events) with retry and backoff, and flushed with keepalive when the page is hidden. 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.
  • Automatic pageviews. The provider tracks page on mount and on every SPA navigation (pushState, replaceState, popstate, de-duplicated by URL). If you already call client.page() on every route change, pass autoPageviews={false}.
  • Automatic attribution. UTM parameters, click ids (gclid, gbraid, wbraid, fbclid, ttclid, msclkid), referrer and landing page are captured automatically.
  • Consent. requireConsent holds back all tracking until client.setConsent({ analytics: true }).
  • StrictMode safe. The provider initialises the client once, even when React runs effects twice in development. When the provider unmounts, it calls client.shutdown().
<TrichiDataProvider apiKey="prj_ak_xxxxxxxxxxxx" autoPageviews requireConsent={false}>
  <App />
</TrichiDataProvider>
function CookieBanner() {
  const client = useTrichiData();
  return <button onClick={() => client.setConsent({ analytics: true })}>Accept</button>;
}

function LogoutButton() {
  const client = useTrichiData();
  return <button onClick={() => client.reset()}>Log out</button>;
}

The device IP is no longer sent from the browser; the server uses the request IP.

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';

function App() {
  const client = useTrichiData();

  useEffect(() => {
    void client.init();
  }, [client]);

  return <Routes />;
}

React-specific exports

ExportPurpose
TrichiDataProviderContext provider with optional auto-init
useTrichiDataHook to access TrichiDataClient
getPageContext()Current page title, url, referrer

Client methods

MethodDescription
init(params?)Start a session (init_sdk)
flush()Send queued events now
shutdown()Stop timers and auto pageviews, then flush once (called by the provider on unmount)
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