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/reactRequires 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
| 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 | — | Override auto-parsed GA/Meta cookies |
autoPageviews | boolean | true | Track page on mount and on every SPA navigation. Set false if you already call client.page() per route |
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). 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 inlocalStorage(in memory when it is unavailable), sent in batches (every 5 s or 20 events) with retry and backoff, and flushed withkeepalivewhen the page is hidden. 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. - Automatic pageviews. The provider tracks
pageon mount and on every SPA navigation (pushState,replaceState,popstate, de-duplicated by URL). If you already callclient.page()on every route change, passautoPageviews={false}. - Automatic attribution. UTM parameters, click ids (
gclid,gbraid,wbraid,fbclid,ttclid,msclkid), referrer and landing page are captured automatically. - Consent.
requireConsentholds back all tracking untilclient.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
| Export | Purpose |
|---|---|
TrichiDataProvider | Context provider with optional auto-init |
useTrichiData | Hook to access TrichiDataClient |
getPageContext() | Current page title, url, referrer |
Client methods
| Method | Description |
|---|---|
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
- Quickstart — track your first event
- Browser SDK — vanilla JS and other frameworks
- REST API — event types and property constraints