React Google Analytics 4 Wrapper

3.0.1 · active · verified Tue Apr 21

React Google Analytics 4 (react-ga4) is a JavaScript library designed to integrate Google Analytics 4 (GA4) tracking into React applications. It provides a straightforward API for initializing GA4 with a measurement ID, sending page views, and tracking custom events. The current stable version is 3.0.1, which introduced significant breaking changes, migrating the library to an ESM-only module with first-class TypeScript support and Vitest for testing. Compared to its predecessor, `react-ga` (which focused on Universal Analytics), `react-ga4` is specifically built for the GA4 data model, removing legacy Universal Analytics (UA) features and streamlining event tracking. It offers a simple migration path from `react-ga` by replacing the import and removing explicit `pageview` calls, as page views are sent by default since v2.0.0. The library focuses on providing a thin, modern wrapper around the gtag.js API for React environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes React GA4, demonstrates how to send a custom page view, and tracks a custom event when a button is clicked. It includes environment variable usage and a simulated route change.

import React from 'react';
import ReactDOM from 'react-dom/client';
import ReactGA from 'react-ga4';

// Replace 'G-YOUR_MEASUREMENT_ID' with your actual GA4 Measurement ID
const GA_MEASUREMENT_ID = process.env.REACT_APP_GA_MEASUREMENT_ID ?? 'G-YOUR_MEASUREMENT_ID';

if (GA_MEASUREMENT_ID) {
  ReactGA.initialize(GA_MEASUREMENT_ID, {
    testMode: process.env.NODE_ENV === 'development' // Optional: enable test mode in development
  });
  console.log('Google Analytics 4 initialized with ID:', GA_MEASUREMENT_ID);
} else {
  console.warn('Google Analytics 4 Measurement ID not found. GA will not be initialized.');
}

function App() {
  React.useEffect(() => {
    // Send an initial pageview when the component mounts
    // Note: ReactGA sends a default pageview on initialize, but this shows manual control.
    ReactGA.send({ hitType: 'pageview', page: window.location.pathname + window.location.search, title: document.title });

    const handleButtonClick = () => {
      ReactGA.event({
        category: 'User Interaction',
        action: 'Click',
        label: 'Submit Button',
        value: 1
      });
      console.log('GA4 event sent: Submit Button Click');
    };

    // Simulate a route change after 2 seconds
    const timeoutId = setTimeout(() => {
      const newPath = '/dashboard';
      ReactGA.send({ hitType: 'pageview', page: newPath, title: 'Dashboard Page' });
      console.log('GA4 pageview sent for:', newPath);
    }, 2000);

    return () => clearTimeout(timeoutId);

  }, []);

  return (
    <div>
      <h1>Welcome to the React GA4 Example!</h1>
      <p>Check your browser's network tab or GA4 debug view for tracking events.</p>
      <button onClick={handleButtonClick}>Send Custom Event</button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

view raw JSON →