react-ga vs react-ga4
Google Analytics Integration in React Applications
react-gareact-ga4

Google Analytics Integration in React Applications

react-ga and react-ga4 are npm packages that provide React-friendly interfaces for integrating Google Analytics into web applications. react-ga targets the older Universal Analytics (analytics.js) platform, while react-ga4 is built specifically for Google Analytics 4 (GA4), which uses a different data model and tracking API based on gtag.js. Both libraries abstract away direct DOM manipulation and offer declarative APIs for tracking pageviews, events, and user interactions within React component lifecycles.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-ga05,105214 kB144-Apache-2.0
react-ga4031884.4 kB443 years agoMIT

Google Analytics in React: react-ga vs react-ga4 — A Practical Guide for Modern Tracking

Integrating Google Analytics into React apps seems straightforward—until you realize there are two major versions of Google Analytics, each with its own JavaScript library and data model. react-ga and react-ga4 reflect this split: one built for the retired Universal Analytics (UA), the other for today’s standard, Google Analytics 4 (GA4). Let’s cut through the confusion and see what really matters for your codebase.

📉 The Core Difference: Universal Analytics vs GA4

react-ga wraps analytics.js, the client-side library for Universal Analytics (UA). UA uses a session-based model centered around “pageviews” and “hits.” It’s been deprecated by Google since July 2023—no new data is processed, and the platform is effectively frozen.

react-ga4 wraps gtag.js, the official library for Google Analytics 4 (GA4). GA4 is event-driven: every interaction (even pageviews) is an event. It supports cross-platform tracking (web + mobile), machine learning insights, and stricter privacy controls.

⚠️ Critical Note: Google stopped processing new data for Universal Analytics on July 1, 2023. If you’re setting up analytics today, only GA4 works. That makes react-ga4 the only viable choice for new implementations.

🔧 Initialization: Setting Up Your Tracker

Both libraries require initializing with a Measurement ID, but the format and underlying script differ.

react-ga (UA property ID format: UA-XXXXXXXXX-X):

import ReactGA from 'react-ga';

ReactGA.initialize('UA-123456789-1');

This loads analytics.js and configures your UA property.

react-ga4 (GA4 Measurement ID format: G-XXXXXXXXXX):

import ReactGA from 'react-ga4';

ReactGA.initialize('G-ABC123DEF45');

This loads gtag.js and sets up your GA4 property. Note the different ID format—using a UA ID here will fail silently.

📄 Tracking Pageviews: Same Goal, Different Syntax

In both systems, you typically track route changes in a router’s useEffect or navigation listener.

react-ga uses pageview():

// In a React component or custom hook
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import ReactGA from 'react-ga';

function usePageTracking() {
  const location = useLocation();

  useEffect(() => {
    ReactGA.pageview(location.pathname + location.search);
  }, [location]);
}

react-ga4 uses send() with an event named 'page_view':

// Same setup, but with react-ga4
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import ReactGA from 'react-ga4';

function usePageTracking() {
  const location = useLocation();

  useEffect(() => {
    ReactGA.send({ hitType: 'pageview', page: location.pathname + location.search });
  }, [location]);
}

Alternatively, react-ga4 also supports a shorthand:

ReactGA.send('pageview'); // Less flexible; doesn’t allow custom path override

But the object form is preferred for control over the tracked path.

🎯 Tracking Events: Parameters and Structure

Event tracking reveals how users interact with buttons, forms, videos, etc. Here’s where GA4’s event-first model changes everything.

react-ga (UA) uses category/action/label/value:

ReactGA.event({
  category: 'User',
  action: 'Clicked Sign Up',
  label: 'Header CTA',
  value: 1
});

These fields are rigid—you can’t add custom parameters without workarounds.

react-ga4 treats everything as an event with arbitrary parameters:

ReactGA.event('sign_up', {
  method: 'Header CTA',
  user_type: 'guest'
});

Notice: no category or action. Instead, you define a meaningful event name ('sign_up') and pass any key-value pairs as parameters. GA4 automatically captures many parameters (like page_location), and you can register custom ones in the GA4 admin interface.

💡 Pro Tip: GA4 reserves certain parameter names (like value, currency). Use them correctly for e-commerce or monetary events.

🛑 Deprecation Reality Check

As confirmed by Google’s official documentation and the npm registry:

  • Universal Analytics (UA) stopped processing new hits on July 1, 2023.
  • react-ga is effectively obsolete for new data collection.
  • GA4 is now the default and only supported version of Google Analytics.

The react-ga npm page includes a warning: “This library is for Universal Analytics... Google Analytics 4 is the newest version...” It’s maintained only for legacy compatibility.

Meanwhile, react-ga4 is actively updated to match GA4’s evolving feature set, including consent mode, debug mode, and enhanced measurement toggles.

🔄 Migration Considerations

If you’re upgrading from react-ga to react-ga4, it’s not a drop-in replacement. You’ll need to:

  1. Replace your UA property ID with a GA4 Measurement ID.
  2. Refactor all event calls to use GA4’s event+parameters model.
  3. Reconfigure goals and conversions in the GA4 dashboard (they don’t auto-migrate).
  4. Update your data layer assumptions—GA4 reports look and behave differently.

Example migration of an event:

// Before (react-ga)
ReactGA.event({
  category: 'Video',
  action: 'Play',
  label: 'Promo Video'
});

// After (react-ga4)
ReactGA.event('video_play', {
  video_title: 'Promo Video',
  content_type: 'promo'
});

✅ When to Use Which?

ScenarioRecommendation
New project in 2024 or laterreact-ga4 — only option that works
Maintaining old app still on UAreact-ga — but plan migration ASAP
Need GA4 features (cross-device, ML insights)react-ga4 — UA doesn’t support these
Building a PWA or SPA with modern toolingreact-ga4 — better alignment with current web standards

💡 Final Advice

Don’t overthink this. Unless you’re stuck supporting a legacy UA property with no migration path, use react-ga4. It’s the present and future of Google Analytics. react-ga belongs in maintenance mode—not new architecture.

And remember: even with the right library, always test your events using GA4’s DebugView or browser dev tools to ensure data flows correctly. No amount of perfect code matters if the tags aren’t firing.

How to Choose: react-ga vs react-ga4

  • react-ga:

    Choose react-ga only if you are maintaining a legacy application still using Universal Analytics (UA), which Google officially stopped processing new data for on July 1, 2023. This package should not be used in new projects, as UA properties are deprecated and no longer receive updates or support from Google. If your organization has not migrated to GA4, this may serve as a temporary bridge during transition, but long-term use is strongly discouraged.

  • react-ga4:

    Choose react-ga4 for all new projects or when migrating existing applications to Google Analytics 4. It aligns with Google’s current analytics infrastructure, supports event-based measurement, enhanced cross-platform tracking, and modern privacy features. Since GA4 is now the default and only supported version of Google Analytics, this package ensures compatibility with current and future reporting capabilities.

README for react-ga

react-ga

React Google Analytics Module

Build Status npm version npm downloads

This is a JavaScript module that can be used to include Google Analytics tracking code in a website or app that uses React for its front-end codebase. It does not currently use any React code internally, but has been written for use with a number of Mozilla Foundation websites that are using React, as a way to standardize our GA Instrumentation across projects.

It is designed to work with Universal Analytics and will not support the older ga.js implementation.

This module is mildly opinionated in how we instrument tracking within our front-end code. Our API is slightly more verbose than the core Google Analytics library, in the hope that the code is easier to read and understand for our engineers. See examples below.

If you use react-ga too, we'd love your feedback. Feel free to file issues, ideas and pull requests against this repo.

Installation

With npm:

npm install react-ga --save

With bower:

bower install react-ga --save

Note that React >= 0.14.0 is needed in order to use the <OutboundLink> component.

Usage

With npm

Initializing GA and Tracking Pageviews:

import ReactGA from 'react-ga';
ReactGA.initialize('UA-000000-01');
ReactGA.pageview(window.location.pathname + window.location.search);

With bower

When included as a script tag, a variable ReactGA is exposed in the global scope.


<!-- The core React library -->
<script src="https://unpkg.com/react@15.5.0/dist/react.min.js"></script>
<!-- The ReactDOM Library -->
<script src="https://unpkg.com/react-dom@15.5.0/dist/react-dom.min.js"></script>
<!-- ReactGA library -->
<script src="/path/to/bower_components/react-ga/dist/react-ga.min.js"></script>

<script>
  ReactGA.initialize('UA-000000-01', { debug: true });
</script>

Demo Code

For a working demo have a look at the demo files or clone this repo and run npm install npm start then open http://localhost:8080 and follow the instructions. Demo requires you to have your own TrackingID.

Upgrading from 1.x to 2.x

You can safely upgrade to 2.x as there are no breaking changes. The main new feature is that the underlying ga function is now exposed via the property ReactGA.ga. This can be helpful when you need a function that ReactGA doesn't support at the moment. Also, for that reason, it is recommended that you rename your imported value as ReactGA rather than ga so as to distinguish between the React GA wrapper and the original ga function.

Community Components

While some convenience components are included inside the package, some are specific to each application. A community curated list of these is available in the wiki: https://github.com/react-ga/react-ga/wiki/Community-Components. Feel free to add any you have found useful.

API

ReactGA.initialize(gaTrackingID, options)

GA must be initialized using this function before any of the other tracking functions will record any data. The values are checked and sent through to the ga('create', ... call.

If you aren't getting any data back from Page Timings, you may have to add siteSpeedSampleRate: 100 to the gaOptions object. This will send 100% of hits to Google Analytics. By default only 1% are sent.

Example
ReactGA.initialize('UA-000000-01', {
  debug: true,
  titleCase: false,
  gaOptions: {
    userId: 123
  }
});

Or with multiple trackers

ReactGA.initialize(
  [
    {
      trackingId: 'UA-000000-01',
      gaOptions: {
        name: 'tracker1',
        userId: 123
      }
    },
    {
      trackingId: 'UA-000000-02',
      gaOptions: { name: 'tracker2' }
    }
  ],
  { debug: true, alwaysSendToDefaultTracker: false }
);
ValueNotes
gaTrackingIDString. Required. GA Tracking ID like UA-000000-01.
options.debugBoolean. Optional. If set to true, will output additional feedback to the console.
options.titleCaseBoolean. Optional. Defaults to true. If set to false, strings will not be converted to title case before sending to GA.
options.gaOptionsObject. Optional. GA configurable create only fields.
options.gaAddressString. Optional. If you are self-hosting your analytics.js, you can specify the URL for it here.
options.alwaysSendToDefaultTrackerBoolean. Optional. Defaults to true. If set to false and using multiple trackers, the event will not be send to the default tracker.
options.testModeBoolean. Optional. Defaults to false. Enables test mode. See here for more information.
options.standardImplementationBoolean. Optional. Defaults to false. Enables loading GA as google expects it. See here for more information.
options.useExistingGaBoolean. Optional. Skips call to window.ga(), assuming you have manually run it.
options.redactEmailBoolean. Optional. Defaults to true. Enables redacting a email as the string that in "Event Category" and "Event Action".

If you are having additional troubles and setting debug = true shows as working please try using the Chrome GA Debugger Extension. This will help you figure out if your implementation is off or your GA Settings are not correct.

ReactGA.set(fieldsObject)

This will set the values of custom dimensions in Google Analytics.

Example
ReactGA.set({ dimension14: 'Sports' });

Or with multiple trackers

ReactGA.set({ userId: 123 }, ['tracker2']);
ValueNotes
fieldsObjectObject. e.g. { userId: 123 }
trackerNamesArray. Optional. A list of extra trackers to run the command on

ReactGA.pageview(path)

Example
ReactGA.pageview('/about/contact-us');

Or with multiple trackers

ReactGA.pageview('/about/contact-us', ['tracker2']);

This will send all the named trackers listed in the array parameter. The default tracker will or will not send according to the initialize() setting alwaysSendToDefaultTracker (defaults to true if not provided).

ValueNotes
pathString. e.g. '/get-involved/other-ways-to-help'
trackerNamesArray. Optional. A list of extra trackers to run the command on
titleString. Optional. e.g. 'Other Ways to Help'

See example above for use with react-router.

ReactGA.modalview(modalName)

A modal view is often an equivalent to a pageview in our UX, but without a change in URL that would record a standard GA pageview. For example, a 'contact us' modal may be accessible from any page in a site, even if we don't have a standalone 'contact us' page on its own URL. In this scenario, the modalview should be recorded using this function.

Example
ReactGA.modalview('/about/contact-us');
ValueNotes
modalNameString. E.g. 'login', 'read-terms-and-conditions'

ReactGA.event(args)

Tracking in-page event interactions is key to understanding the use of any interactive web property. This is how we record user interactions that don't trigger a change in URL.

Examples
ReactGA.event({
  category: 'User',
  action: 'Created an Account'
});

ReactGA.event({
  category: 'Social',
  action: 'Rated an App',
  value: 3
});

ReactGA.event({
  category: 'Editing',
  action: 'Deleted Component',
  label: 'Game Widget'
});

ReactGA.event({
  category: 'Promotion',
  action: 'Displayed Promotional Widget',
  label: 'Homepage Thing',
  nonInteraction: true
});
ValueNotes
args.categoryString. Required. A top level category for these events. E.g. 'User', 'Navigation', 'App Editing', etc.
args.actionString. Required. A description of the behaviour. E.g. 'Clicked Delete', 'Added a component', 'Deleted account', etc.
args.labelString. Optional. More precise labelling of the related action. E.g. alongside the 'Added a component' action, we could add the name of a component as the label. E.g. 'Survey', 'Heading', 'Button', etc.
args.valueInt. Optional. A means of recording a numerical value against an event. E.g. a rating, a score, etc.
args.nonInteractionBoolean. Optional. If an event is not triggered by a user interaction, but instead by our code (e.g. on page load), it should be flagged as a nonInteraction event to avoid skewing bounce rate data.
args.transportString. Optional. This specifies the transport mechanism with which hits will be sent. Valid values include 'beacon', 'xhr', or 'image'.

ReactGA.timing(args)

Allow to measure periods of time such as AJAX requests and resources loading by sending hits using the analytics.js library. For more detailed description, please refer to https://developers.google.com/analytics/devguides/collection/analyticsjs/user-timings.

Example

Usage:

ReactGA.timing({
  category: 'JS Libraries',
  variable: 'load',
  value: 20, // in milliseconds
  label: 'CDN libs'
});

This is equivalent to the following Google Analytics command:

ga('send', 'timing', 'JS Libraries', 'load', 20, 'CDN libs');
ValueNotes
args.categoryString. Required. A string for categorizing all user timing variables into logical groups.
args.variableString. Required. Name of the variable being recorded.
args.valueInt. Required. Number of milliseconds elapsed time to report.
args.labelString. Optional. It can be used to add flexibility in visualizing user timings in the reports.

ReactGA.ga()

The original ga function can be accessed via this method. This gives developers the flexibility of directly using ga.js features that have not yet been implemented in ReactGA. No validations will be done by ReactGA as it is being bypassed if this approach is used.

If no arguments are passed to ReactGA.ga(), the ga object is returned instead.

Example

Usage with arguments:

ReactGA.ga('send', 'pageview', '/mypage');

Usage without arguments:

var ga = ReactGA.ga();
ga('send', 'pageview', '/mypage');

ReactGA.outboundLink(args, hitCallback)

Tracking links out to external URLs (including id.webmaker.org for OAuth 2.0 login flow). A declarative approach is found in the next section, by using an <OutboundLink> component.

Example
ReactGA.outboundLink(
  {
    label: 'Clicked Create an Account'
  },
  function () {
    console.log('redirect here');
  },
  ['tracker2']
);
ValueNotes
args.labelString. Required. Description of where the outbound link points to. Either as a URL, or a string.
hitCallbackfunction. The react-ga implementation accounts for the possibility that GA servers are down, or GA is blocked, by using a fallback 250ms timeout. See notes in GA Dev Guide
trackerNamesArray<String> Optional. A list of extra trackers to run the command on.

<OutboundLink> Component

Outbound links can directly be used as a component in your React code and the event label will be sent directly to ReactGA.

Example
var ReactGA = require('react-ga');

render() {
  return (
    <div>
      <ReactGA.OutboundLink
        eventLabel="myLabel"
        to="http://www.example.com"
        target="_blank"
        trackerNames={['tracker2']}
      >
        My Link
      </ReactGA.OutboundLink>
    </div>
  );
}
ValueNotes
eventLabelString. Required. Description of where the outbound link points to. Either as a URL, or a string.
toString. Required. URL the link leads to.
targetString. Optional. To open the link in a new tab, use a value of _blank.
trackerNamesArray<String> Optional. A list of extra trackers to run the command on.

For bower, use the <ReactGA.OutboundLink> component.

ReactGA.exception(args)

GA exception tracking

Example
ReactGA.exception({
  description: 'An error occurred',
  fatal: true
});
ValueNotes
args.descriptionString. Optional. Description of what happened.
args.fatalboolean. Optional. Set to true if it was a fatal exception.

ReactGA.plugin.require(name, [options])

Require GA plugins.

Example
ReactGA.plugin.require('localHitSender', { path: '/log', debug: true });
ValueNotes
nameString. Required. The name of the plugin to be required. Note: if the plugin is not an official analytics.js plugin, it must be provided elsewhere on the page.
optionsObject. Optional. An initialization object that will be passed to the plugin constructor upon instantiation.

ReactGA.plugin.execute(pluginName, action, [actionType], [payload])

Execute the action for the pluginName with the payload.

Example
ReactGA.plugin.execute('ecommerce', 'addTransaction', {
  id: 'jd38je31j',
  revenue: '3.50'
});

You can use this function with four arguments to pass actionType and payload along with executed action

Example
ReactGA.plugin.execute('ec', 'setAction', 'purchase', {
  id: 'jd38je31j',
  revenue: '3.50'
});

Test Mode

To enable test mode, initialize ReactGA with the testMode: true option. Here's an example from tests/utils/testMode.test.js

// This should be part of your setup
ReactGA.initialize('foo', { testMode: true });
// This would be in the component/js you are testing
ReactGA.ga('send', 'pageview', '/mypage');
// This would be how you check that the calls are made correctly
expect(ReactGA.testModeAPI.calls).toEqual([
  ['create', 'foo', 'auto'],
  ['send', 'pageview', '/mypage']
]);

Standard Implementation

To enable standard implemention of google analytics.

Add this script to your html

<!-- Google Analytics -->
<script>
  (function (i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    (i[r] =
      i[r] ||
      function () {
        (i[r].q = i[r].q || []).push(arguments);
      }),
      (i[r].l = 1 * new Date());
    (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]);
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m);
  })(
    window,
    document,
    'script',
    '<%=htmlWebpackPlugin.options.analyticsURL%>',
    'ga'
  );
  ga('create', 'UA-XXX-X', 'auto');
  ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

Initialize ReactGA with standardImplementation: true option.

// This should be part of your setup
ReactGA.initialize('UA-XXX-X', { standardImplementation: true });

Development

Prerequisites

  • node.js
  • npm
  • npm install
  • npm install react@^15.6.1 prop-types@^15.5.10 - This is for the optional dependencies.

To Test

npm test

Submitting changes/fixes

Follow instructions inside CONTRIBUTING.md


Acknowledgements