Declarative Tracking for React Apps

9.3.2 · active · verified Sun Apr 19

react-tracking is a declarative and imperative tracking library specifically designed for React applications. It provides an analytics platform-agnostic solution, empowering developers to manage and dispatch user interaction data effectively. The library's core philosophy is to compartmentalize tracking concerns directly within individual components, thereby preventing data leakage and ensuring a clean separation of concerns across the entire application. It offers a dual API approach, supporting both the traditional Higher-Order Component (HoC) or decorator pattern and a modern React Hooks API, which was fully introduced in version 8.1.0 for functional components. The current stable version, 9.3.2, has recently addressed compatibility issues with React Native environments and re-enabled support for Node.js 16.9+. Developed by The New York Times, react-tracking is actively maintained, with a consistent cadence of patch and minor releases addressing bug fixes and introducing new features like `mergeOptions` (v9.3.0) and `deepmerge` re-export (v9.2.0). Its key differentiators include its highly declarative nature, flexibility to integrate seamlessly with virtually any analytics backend, and comprehensive support for both class-based and modern functional React components, making it a versatile choice for instrumenting React UIs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `useTracking` hook to declare component-level tracking data, imperatively dispatch events with `trackEvent`, access contextual data with `getTrackingData`, and use the `<Track>` component to propagate context to child components. It also shows options like `dispatchOnMount` and `mergeOptions`.

import React, { useEffect } from 'react';
import { useTracking, Track } from 'react-tracking';

interface MyComponentProps {
  userId: string;
  pageName: string;
}

const ProductPage: React.FC<MyComponentProps> = ({ userId, pageName }) => {
  // Initialize tracking for this component, passing contextual data
  const { Track, trackEvent, getTrackingData } = useTracking(
    {
      page: pageName,
      user: userId,
      environment: process.env.NODE_ENV ?? 'development',
    },
    {
      // Optional: Dispatch tracking data when component mounts
      dispatchOnMount: true,
      // Optional: Custom merge options for tracking objects (since v9.3.0)
      mergeOptions: {
        isMergeableObject: obj => !(obj instanceof Date || obj instanceof RegExp),
      },
    }
  );

  useEffect(() => {
    // Example: Log current tracking data when component mounts
    console.log('Current tracking context:', getTrackingData());
  }, []);

  const handleProductClick = (productId: string) => {
    // Imperatively dispatch an event
    trackEvent({
      action: 'product_click',
      productId: productId,
      timestamp: new Date().toISOString(),
    });
  };

  return (
    <Track> {/* Use <Track> to pass context to children */}
      <div>
        <h1>{pageName} for User: {userId}</h1>
        <p>This is a product page example.</p>
        <button onClick={() => handleProductClick('product-123')}>
          Click to Track Product 123
        </button>
        <button onClick={() => trackEvent({ action: 'promo_view', promoId: 'summer_sale' })}>
          Track Promo View
        </button>
      </div>
    </Track>
  );
};

// Example of usage:
// <ProductPage userId="user-abc" pageName="Electronics-Category" />
export default ProductPage;

view raw JSON →