React Google Analytics Module (Universal Analytics)

3.3.1 · deprecated · verified Sun Apr 19

react-ga is a JavaScript module designed for integrating Google Universal Analytics (UA-xxxxxx-x properties) tracking into React applications. It provides a React-friendly wrapper around the core Google Analytics library, offering an opinionated API to standardize instrumentation. The current stable version is 3.3.1, released in June 2022. However, this library is now considered deprecated because Google Universal Analytics ceased processing new hits on July 1, 2023, in favor of Google Analytics 4 (GA4). react-ga does not support GA4's `G-` measurement IDs, making it unsuitable for new analytics implementations or existing ones that have migrated to GA4. For GA4 integration, users should consider `react-ga4` or direct `gtag.js` implementations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `react-ga` with a Universal Analytics tracking ID and send a pageview and a custom event. It includes a warning for users attempting to use GA4 IDs.

import ReactGA from 'react-ga';
import React, { useEffect } from 'react';

const GA_TRACKING_ID = process.env.REACT_APP_GA_UA_ID ?? 'UA-000000-01'; // Use a Universal Analytics ID

function App() {
  useEffect(() => {
    if (GA_TRACKING_ID.startsWith('UA-')) {
      ReactGA.initialize(GA_TRACKING_ID, { debug: process.env.NODE_ENV === 'development' });
      ReactGA.pageview(window.location.pathname + window.location.search);
      console.log('ReactGA initialized and pageview sent for UA ID:', GA_TRACKING_ID);
    } else {
      console.warn('GA_TRACKING_ID is not a Universal Analytics ID (UA-). react-ga only supports Universal Analytics. Please use react-ga4 for GA4 (G-) IDs.');
    }
  }, []);

  const handleButtonClick = () => {
    if (GA_TRACKING_ID.startsWith('UA-')) {
      ReactGA.event({
        category: 'User',
        action: 'Clicked Button',
        label: 'Demo Button'
      });
      console.log('GA Event sent: Clicked Demo Button');
    }
  };

  return (
    <div>
      <h1>Welcome to React-GA Demo</h1>
      <p>This demo uses react-ga for Universal Analytics tracking.</p>
      <button onClick={handleButtonClick}>Track Me</button>
      <p>Check your Universal Analytics dashboard for data.</p>
      <p>Note: Universal Analytics is deprecated. For GA4, use react-ga4.</p>
    </div>
  );
}

export default App;

view raw JSON →