npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-event-tracking

v2.0.7

Published

A convenient React context for tracking analytics events.

Readme

react-event-tracking NPM Version

A convenient React context for tracking analytics events.

Features

  • Elegant Type-Safe Api: enjoy a seamless dot-notation experience with full TypeScript autocompletion.
  • Nested Contexts: Automatically merges parameters from parent providers.
  • Zero Re-renders: No need to wrap props in useCallback/useMemo.
  • Multiple Providers: Send events to different analytics services.
  • Event Filtering: Control which events are sent to which provider.
  • Event Transformation: Modify event names or parameters before they are sent to provider.

Table of Contents

Installation

npm install react-event-tracking
yarn add react-event-tracking

Quickstart

  1. Define the root handler (e.g., send to GTM, Amplitude or API)
import { TrackRoot } from 'react-event-tracking';

const Main = () => (
  <TrackRoot onEvent={(name, params) => gtag('event', name, params)}>
    <App/>
  </TrackRoot>
);
  1. Wrap any component with shared parameters
import { TrackProvider } from 'react-event-tracking';

const Dashboard = () => (
  <TrackProvider params={{ screen: 'dashboard' }}>
    <DashboardView/>
  </TrackProvider>
);

Usage Guide

Basic Hook

Use useReactEventTracking for simple event tracking

import { useReactEventTracking } from 'react-event-tracking';

const MyButton = () => {
  const { track } = useReactEventTracking();

  return (
    {/* Option A: String } */}
    <button onClick={() => track('click', { button_id: '123' })}>
      Click me
    </button>

    {/* Option B: Object call */} 
    <button onClick={() => track({ eventName: 'click', params: { button_id: '456' } })}>
      Click me
    </button>

  );
};

Typed Hook Factory

For a more convenient dot-notation syntax and full TypeScript support, create your own hook using createReactEventTrackingHook.

  1. Create a hook:
import { createReactEventTrackingHook } from 'react-event-tracking';

// LoadingScreen.tsx
export type LoginScreenEvents = {
	forgot_password: { from: "footer" | "button" }
	logged_in: { timePassed: number }
}

type SystemEvents = {
	app_updated: { previous_version: string; current_version: string }
}

// analytics.ts
export type AnalyticsEvents = SystemEvents & {
  // supports deeply nested event maps
	login_screen: LoginScreenEvents
}

export const useTracking = createReactEventTrackingHook<AnalyticsEvents>();
  1. Use it in your components:
const LoginButton = () => {
  // You can use the full tracker
  const { track } = useTracking();
  
  // Or narrow it down to a specific scope
  const { track: track2 } = useTracking("login_screen");

  const handleLogin = () => {
    // Full path: eventName is derived from the call chain (result: "login_screen.logged_in")      
    track.login_screen.logged_in({ timePassed: 3000 });
    
    // Narrowed path: the same result: "login_screen.logged_in":
    track2.logged_in({ timePassed: 3000 });
  };
  
  return (    
    <button onClick={handleLogin}>
      Login with Google
    </button>
  );
};

Custom Handlers

Sometimes you need to expose more than just the track function, for example, a way to identify users. You can pass custom handlers to the factory.

  1. Define your handlers type and create the hook:
type MyCustomHandlers = {
  setUserId: (id: string) => void;
}

export const useTracking = createReactEventTrackingHook<AnalyticsEvents, MyCustomHandlers>();
  1. Create a custom Root using TrackRoot.factory:
import { TrackRoot } from 'react-event-tracking';

const CustomTrackRoot = TrackRoot.factory<MyCustomHandlers>({
  onEvent: (name, params) => {
    amplitude.logEvent(name, params);
  },
  customHandlers: {
    setUserId: (id) => {
      amplitude.setUserId(id);
    }
  }
});

const App = () => (
  <CustomTrackRoot>
    <Main />
  </CustomTrackRoot>
);
  1. Use it in your components:
const Profile = () => {
  const { track, setUserId } = useTracking();

const handleLogin = () => {
    track.login_screen.logged_in({ timePassed: 3000 });
    setUserId('user_123')
  };

  return (
    <button onClick={handleLogin}>
      Login
    </button>
  );
}

Standalone Tracking Function

If you need to use the typed tracking API outside of React components, you can use createEventTrackingStandalone. It provides the same dot-notation and type safety as the hook factory.

import { createEventTrackingStandalone } from 'react-event-tracking';
import { AnalyticsEvents } from './analytics'; // Your events map

// Provide your base tracking implementation
const baseTrack = (eventName: string, params?: Record<string, any>) => {
  amplitude.logEvent(eventName, params);
};

export const trackEvent = createEventTrackingStandalone<AnalyticsEvents>(baseTrack);

// Use it anywhere
trackEvent.login_screen.logged_in({ timePassed: 3000 });

Typed Event Factory

Best for untyped methods

import { createEventFactory, useMountEvent } from 'react-event-tracking';
import { AnalyticsEvents } from './analytics'; // Your events map

export const eventFactory = createEventFactory<AnalyticsEvents>();

// page.tsx
export function LoginPage() {
  // Creates { eventName: 'login_screen.show', params: {} }        
  useMountEvent(eventFactory.login_screen.show({}))

  return ...
}

Advanced Usage

Multiple Trackers & Factory

You can chain multiple TrackRoot components to send events to different analytics services. Events bubble up through all providers.

Use TrackRoot.factory to create reusable tracker components:

  1. Create specific trackers
const TrackRootGoogle = TrackRoot.factory({
  onEvent: (name, params) => gtag('event', name, params)
});

const TrackRootAmplitude = TrackRoot.factory({
  onEvent: (name, params) => amplitude.logEvent(name, params)
});
  1. Compose them in your app
const App = () => (
  <TrackRootGoogle>
    <TrackRootAmplitude>
      <MyApp />
    </TrackRootAmplitude>
  </TrackRootGoogle>
);

Filtering Events

You can control which events are sent to which provider using the filter prop in factory. If the filter returns false, the event is skipped for that tracker but continues to bubble up to others.

// Google Analytics: only track page_* events
const TrackRootGoogle = TrackRoot.factory({
  onEvent: (name, params) => gtag('event', name, params),
  filter: (name) => name.startsWith('page_')
});

// Amplitude: track everything
const TrackRootAmplitude = TrackRoot.factory({
  onEvent: (name, params) => amplitude.logEvent(name, params),
});

Compose them in your app:

const App = () => (
  <TrackRootGoogle>
    <TrackRootAmplitude>
      <MyApp />
    </TrackRootAmplitude>
  </TrackRootGoogle>
);

Transforming Events

You can modify the event name or parameters before they are sent to the handler using the transform prop in factory.

Note: Transformations apply locally and do not affect the event bubbling up to parent providers.

// GDPR Tracker
const AmplitudeUS = TrackRoot.factory({
  onEvent: (name, params) => amplitude.logEvent(name, params),
  transform: (name, params) => {
    if (params?.userRegion === 'EU') {
      // Remove PII (Personally Identifiable Information)
      const { userId, email, ...safeParams } = params;
      return { 
        eventName: name, 
        params: safeParams 
      };
    }
    return { eventName: name, params };
  }
});

TypeScript Generics Support

TrackProvider supports generics for strict typing of the passed parameters.

interface ScreenParams {
  screen: "dashboard" | "authScreen"
}

const MyPage = () => (
  <TrackProvider<ScreenParams> params={{ screen: 'dashboard' }}>
    <Content />
  </TrackProvider>
);

Best Practices

A common pattern is to layer data from global to specific. Here is how parameters merge:

<TrackRoot onEvent={handleEvent}>
  {/* 1. ROOT: Global data (App Version, Environment) */}
  <TrackProvider params={{ appVersion: '1.0.0' }}>
  
    {/* 2. PAGE: Screen-level context */}
    <TrackProvider params={{ page: 'ProductDetails', category: 'Shoes' }}>
    
      {/* 3. COMPONENT: Widget-level context */}
      <TrackProvider params={{ productId: 'sku-999' }}>
        <AddToCartButton />
      </TrackProvider>

    </TrackProvider>
  </TrackProvider>
</TrackRoot>

// Inside AddToCartButton:
const { track } = useReactEventTracking();

// 4. EVENT: Action-specific data
// When clicked, we only pass what changed right now.
const handleClick = () => {
  track('add_to_cart', { quantity: 1 });
};

Resulting Event Payload: The library merges all layers automatically. The handler receives:

{
  // From Root
  appVersion: '1.0.0',
  // From Page Provider
  page: 'ProductDetails',
  category: 'Shoes',
  // From Component Provider
  productId: 'sku-999',
  // From Event
  quantity: 1
}

Built-in Hooks

useMountEvent

Sends an event when the component mounts.

import { useMountEvent } from 'react-event-tracking';

export function DashboardScreen(props) {
    useMountEvent('page_view', { screen: 'dashboard' });

    return <div>Dashboard</div>;
}

Built-in Components

The library provides convenient wrapper components for declarative event tracking without writing custom hooks or useEffect.

Track.OnMount

Sends an event when the component mounts. It can wrap children or be used as a standalone component. You can pass an event object (for example, generated by the Typed Event Factory).

import { Track } from 'react-event-tracking';
import { eventFactory } from './analytics';

export function DashboardScreen() {
  return (
    <>
      {/* Option A: String and params */}
      <Track.OnMount event="page_view" params={{ screen: 'dashboard' }}>
        <div>Dashboard</div>
      </Track.OnMount>

      {/* Option B: Event object using Typed Event Factory */}
      <Track.OnMount event={eventFactory.login_screen.show({})}>
        <div>Dashboard</div>
      </Track.OnMount>
    </>
  );
}

Track.OnImpression

Sends an event when the wrapped element becomes visible in the viewport. It uses IntersectionObserver under the hood. By default, it triggers only once (freezeOnceVisible: true). You can also pass an event object here.

import { Track } from 'react-event-tracking';
import { eventFactory } from './analytics';

export function ProductList() {
  return (
    <div>
      {/* Option A: String and params */}
      <Track.OnImpression 
        event="product_viewed" 
        params={{ productId: '123' }}
        options={{ threshold: 0.5 }} // triggers when 50% visible
      >
        <div className="product-card">
          Product 123
        </div>
      </Track.OnImpression>

      {/* Option B: Event object using Typed Event Factory */}
      <Track.OnImpression 
        event={eventFactory.ui.button_click({ id: '123' })}
        options={{ threshold: 0.5 }}
      >
        <div className="product-card">
          Product 123
        </div>
      </Track.OnImpression>
    </div>
  );
}