Skip to content

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

bash
npm install @kitbase/analytics-react
bash
pnpm add @kitbase/analytics-react
bash
yarn add @kitbase/analytics-react

Setup

Wrap your application with KitbaseAnalyticsProvider. The SDK initializes eagerly so auto-tracking is active immediately.

tsx
// 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.

tsx
<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.

FeatureConfig KeyWhat It Tracks
Page viewsautoTrackPageViewsInitial load + SPA navigations (pushState / popstate)
ClicksautoTrackClicksClicks on buttons, links, inputs, and other interactive elements
Outbound linksautoTrackOutboundLinksClicks on links to external domains
Scroll depthautoTrackScrollDepthMaximum scroll percentage per page
Element visibilityautoTrackVisibilityTime an element is visible in the viewport (via data attributes)
Frustration signalsautoDetectFrustrationRage clicks (3+ rapid clicks) and dead clicks (no DOM change)
Web VitalsautoTrackWebVitalsLCP, 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:

tsx
<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:

tsx
<div data-kb-track-visibility="Pricing Section Viewed"
     data-kb-visibility-channel="marketing"
     data-kb-visibility-threshold="0.75">
  Pricing details...
</div>
AttributeDescription
data-kb-track-clickEvent name fired on click
data-kb-click-channelChannel for the click event (default: 'engagement')
data-kb-track-visibilityEvent name fired when element leaves viewport
data-kb-visibility-channelChannel for the visibility event (default: 'engagement')
data-kb-visibility-thresholdIntersectionObserver threshold 0–1 (default: 0.5)

Using the Hooks

All hooks must be called inside a component wrapped by KitbaseAnalyticsProvider.

tsx
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.

tsx
const track = useTrack();
track({ channel: 'ui', event: 'Button Clicked', tags: { location: 'header' } });

usePageView()

Returns a memoized function to track page views manually.

tsx
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.

tsx
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.

tsx
const trackRevenue = useRevenue();
trackRevenue({ amount: 1999, currency: 'USD', tags: { plan: 'premium' } });

User Identity

useIdentify()

Returns a memoized function to identify users.

tsx
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.

tsx
const userId = useUserId();

useReset()

Returns a function to clear the user identity (typically on logout).

tsx
const reset = useReset();
reset();

Super Properties

useSuperProperties(properties, deps?)

Registers properties that are included in every subsequent event. Re-registers when deps change.

tsx
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.

tsx
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.

tsx
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:

tsx
import {
  type KitbaseConfig,
  type TrackOptions,
  type TrackResponse,
  type PageViewOptions,
  type RevenueOptions,
  type IdentifyOptions,
  type KitbasePlugin,
  KitbaseError,
  ValidationError,
} from '@kitbase/analytics-react';

Next Steps

Released under the MIT License.