React Integration
The @kitbase/analytics-react package wraps the core SDK with a React Context provider and a set of hooks for idiomatic React usage.
React 17+
The package uses the react-jsx transform and requires React 17 or later.
Installation
npm install @kitbase/analytics-reactpnpm add @kitbase/analytics-reactyarn add @kitbase/analytics-reactSetup
Wrap your application with KitbaseAnalyticsProvider. The SDK initializes eagerly so auto-tracking is active immediately.
// main.tsx / App.tsx
import { KitbaseAnalyticsProvider } from '@kitbase/analytics-react';
function App() {
return (
<KitbaseAnalyticsProvider config={{ sdkKey: 'YOUR_SDK_KEY' }}>
<YourApp />
</KitbaseAnalyticsProvider>
);
}INFO
SDK keys are public and safe to commit to source control. They are used only to identify which project to send traffic to and do not grant access to your data.
Configuration Options
All options beyond sdkKey are optional. Sensible defaults are applied automatically.
<KitbaseAnalyticsProvider
config={{
sdkKey: 'YOUR_SDK_KEY',
debug: false,
analytics: {
autoTrackPageViews: true, // Tracks pushState / popstate navigations
autoTrackClicks: true, // Tracks clicks on interactive elements
autoTrackOutboundLinks: true, // Tracks clicks on external links
autoTrackScrollDepth: true, // Tracks max scroll depth per page
autoTrackVisibility: true, // Tracks element visibility via data attributes
autoTrackWebVitals: false, // Requires 'web-vitals' package
autoDetectFrustration: true, // Detects rage clicks and dead clicks
},
offline: {
enabled: false,
maxQueueSize: 1000,
flushInterval: 30000, // 30 seconds
flushBatchSize: 50,
maxRetries: 3,
},
botDetection: {
enabled: true,
},
}}
>
<YourApp />
</KitbaseAnalyticsProvider>Auto-Tracking
Everything below is enabled by default — no manual wiring needed. The SDK patches history.pushState and listens for popstate, so React Router navigations are captured automatically.
| Feature | Config Key | What It Tracks |
|---|---|---|
| Page views | autoTrackPageViews | Initial load + SPA navigations (pushState / popstate) |
| Clicks | autoTrackClicks | Clicks on buttons, links, inputs, and other interactive elements |
| Outbound links | autoTrackOutboundLinks | Clicks on links to external domains |
| Scroll depth | autoTrackScrollDepth | Maximum scroll percentage per page |
| Element visibility | autoTrackVisibility | Time an element is visible in the viewport (via data attributes) |
| Frustration signals | autoDetectFrustration | Rage clicks (3+ rapid clicks) and dead clicks (no DOM change) |
| Web Vitals | autoTrackWebVitals | LCP, CLS, INP, FCP, TTFB (requires web-vitals package) |
Data Attributes
Use data attributes for declarative tracking without writing JavaScript.
Click tracking — fires a custom event when the element is clicked:
<button data-kb-track-click="CTA Clicked"
data-kb-click-channel="marketing">
Sign Up
</button>Visibility tracking — measures how long an element is visible in the viewport:
<div data-kb-track-visibility="Pricing Section Viewed"
data-kb-visibility-channel="marketing"
data-kb-visibility-threshold="0.75">
Pricing details...
</div>| Attribute | Description |
|---|---|
data-kb-track-click | Event name fired on click |
data-kb-click-channel | Channel for the click event (default: 'engagement') |
data-kb-track-visibility | Event name fired when element leaves viewport |
data-kb-visibility-channel | Channel for the visibility event (default: 'engagement') |
data-kb-visibility-threshold | IntersectionObserver threshold 0–1 (default: 0.5) |
Using the Hooks
All hooks must be called inside a component wrapped by KitbaseAnalyticsProvider.
import { useTrack, useIdentify, useRevenue } from '@kitbase/analytics-react';
function Checkout({ order }: { order: Order }) {
const track = useTrack();
const identify = useIdentify();
const trackRevenue = useRevenue();
async function onPurchase() {
await track({
channel: 'payments',
event: 'Purchase Completed',
tags: { amount: order.total, items: order.items.length },
});
await trackRevenue({
amount: order.total,
currency: order.currency,
});
}
return <button onClick={onPurchase}>Complete Purchase</button>;
}Hooks Reference
Event Tracking
useTrack()
Returns a memoized function to track custom events.
const track = useTrack();
track({ channel: 'ui', event: 'Button Clicked', tags: { location: 'header' } });usePageView()
Returns a memoized function to track page views manually.
const trackPageView = usePageView();
// Usually automatic — call manually only if needed
trackPageView({ path: '/custom-path' });useAutoPageView(options?, deps?)
Automatically tracks a page view on mount and whenever deps change.
function ProductPage({ productId }: { productId: string }) {
useAutoPageView(
{ tags: { product_id: productId } },
[productId]
);
return <div>Product {productId}</div>;
}useRevenue()
Returns a memoized function to track revenue events.
const trackRevenue = useRevenue();
trackRevenue({ amount: 1999, currency: 'USD', tags: { plan: 'premium' } });User Identity
useIdentify()
Returns a memoized function to identify users.
const identify = useIdentify();
await identify({
userId: 'user_123',
traits: { email: 'user@example.com', plan: 'premium' },
});See Identify Users for more on how identity resolution works.
useUserId()
Returns the current identified user ID, or null.
const userId = useUserId();useReset()
Returns a function to clear the user identity (typically on logout).
const reset = useReset();
reset();Super Properties
useSuperProperties(properties, deps?)
Registers properties that are included in every subsequent event. Re-registers when deps change.
function App({ user }: { user: User }) {
useSuperProperties(
{ user_type: user.type, plan: user.plan },
[user.type, user.plan]
);
return <MainContent />;
}For registerOnce, unregister, getSuperProperties, and clearSuperProperties, use the instance directly via useKitbaseAnalytics().
Time Events
useTimeEvent(eventName)
Returns an object with start, stop, and getDuration to measure event duration.
function VideoPlayer() {
const { start } = useTimeEvent('Video Watched');
const track = useTrack();
return (
<video
onPlay={start}
onEnded={() => track({
channel: 'engagement',
event: 'Video Watched',
// $duration automatically included
})}
/>
);
}Direct Instance Access
For features not covered by the convenience hooks (plugins, debug mode, timed event listing, etc.), use useKitbaseAnalytics() to get the raw KitbaseAnalytics instance.
import { useKitbaseAnalytics, WebVitalsPlugin } from '@kitbase/analytics-react';
function PluginLoader() {
const kitbase = useKitbaseAnalytics();
useEffect(() => {
kitbase.use(new WebVitalsPlugin());
}, [kitbase]);
return null;
}Available instance methods include register, registerOnce, unregister, getSuperProperties, clearSuperProperties, timeEvent, getTimedEvents, getEventDuration, cancelTimeEvent, trackOutboundLink, use, getPlugins, setDebugMode, isDebugMode, shutdown, and getInstance. See the JavaScript SDK for full details.
Re-exported Types
All types, errors, and utilities from @kitbase/analytics are re-exported, so you can import everything from a single package:
import {
type KitbaseConfig,
type TrackOptions,
type TrackResponse,
type PageViewOptions,
type RevenueOptions,
type IdentifyOptions,
type KitbasePlugin,
KitbaseError,
ValidationError,
} from '@kitbase/analytics-react';Next Steps
- Autocapture — Full reference of automatically tracked events
- Custom Events — Channels, tags, and notifications
- Identify Users — Identity resolution and user properties
- JavaScript SDK — Full SDK reference including offline support