Skip to main content

React

Installation

npm install @haya/analytics

Initialize once at the app root

Initialize Haya in your top-level component or entry file so it runs once when the app mounts. Do not initialize inside components that re-render.

// src/main.tsx (Vite) or src/index.tsx (CRA)
import React from 'react';
import ReactDOM from 'react-dom/client';
import haya from '@haya/analytics';
import App from './App';

haya.init(import.meta.env.VITE_HAYA_SDK_KEY, {
sessionReplay: true,
heatmaps: true,
autoTrack: { clicks: true, scrolls: true, pageviews: true },
maskInputs: true,
});

ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);

Add your SDK key to .env:

# .env
VITE_HAYA_SDK_KEY=your_sdk_key_here

:::info Public environment variables Vite exposes variables prefixed with VITE_ to the browser. Your SDK key is a public identifier — it's safe to include in frontend code. See Security. :::

Tracking custom events

Call haya.track() anywhere in your components:

import haya from '@haya/analytics';

function PricingPage() {
const handleUpgrade = (plan: string) => {
haya.track('upgrade_clicked', { plan });
// ... your upgrade logic
};

return (
<button onClick={() => handleUpgrade('pro')}>
Upgrade to Pro
</button>
);
}

SPA page tracking

Haya automatically patches history.pushState and listens to popstate, so React Router navigation is tracked automatically — no extra setup needed.

If you need to manually fire a pageview (e.g. after a programmatic navigation):

import haya from '@haya/analytics';

haya.track('pageview', { url: window.location.href });

Resetting on logout

When a user logs out, call haya.reset() to flush remaining events and tear down the SDK. You can re-initialize it afterward if needed:

async function handleLogout() {
haya.flush(); // send any buffered events
await logout();
haya.reset();
}

React strict mode

React 18 Strict Mode double-invokes effects in development. Haya guards against double initialization:

if (isInitialized) {
warn("Haya SDK is already initialized. Call haya.reset() first.");
return;
}

So you won't get duplicate tracking even in Strict Mode.