You can add Google Analytics 4 to a React application by loading the gtag.js script via the react-ga4 npm package. This library provides a thin React-friendly wrapper that initialises your measurement ID and lets you send pageviews and events with simple method calls.
Below you will install the package, choose between automatic and manual page view tracking for your single-page app, dispatch custom events, and configure consent mode alongside testing in GA4 DebugView.
The React GA4 Package Vs The Google Tag
The official way to instrument a website for Google Analytics 4 is the Google tag (gtag.js). You can paste its snippet into a React app's index.html, but that leaves you managing the global gtag function and script loading outside React's component lifecycle. The react-ga4 community package, released under the MIT licence and maintained by Han Lin Yap, loads gtag.js from https://www.googletagmanager.com/gtag/js unless you override it with the gtagUrl option. You initialise it once with your measurement ID and then call methods such as ReactGA.send, ReactGA.event or ReactGA.gtag from any component. Under the hood the wrapper issues gtag commands, and ReactGA.gtag passes raw commands straight through.
The package supports multiple trackers: pass an array of objects, each with a trackingId and optional gaOptions (gtag config fields) and gtagOptions (additional gtag options). You can set a nonce for Content Security Policy compliance and there is a testMode boolean (default false). The gtagUrl option changes where gtag.js is loaded from. For advanced use, you can extend the base class via import { ReactGAImplementation } from "react-ga4" and override its methods.
Installing And Initialising
1. Install the package
Run npm i react-ga4 in your project directory.
2. Initialise GA4 early
Import ReactGA from "react-ga4" and call ReactGA.initialize in your root file (index.js or App.js) before React mounts. You need your GA4 measurement ID, a string like G-XXXXXXX. Find it in Admin > Data streams.
import ReactGA from "react-ga4";
ReactGA.initialize("G-XXXXXXXXXX");
// Optionally pass options:
ReactGA.initialize("G-XXXXXXXXXX", {
testMode: false, // default
nonce: "...", // CSP nonce
gtagUrl: "https://www.googletagmanager.com/gtag/js",
gaOptions: { /* gtag config fields */ },
gtagOptions: { /* additional gtag options */ }
});If you need to send data to multiple GA4 properties, pass an array of tracker objects:
ReactGA.initialize([
{ trackingId: "G-111AAA", gaOptions: { ... } },
{ trackingId: "G-222BBB" }
]);After initialisation the global gtag function is ready, and you can send events or page views immediately. The ReactGA.gtag() method lets you issue any raw gtag command if the provided wrapper methods don't cover your use case.
Short on time? Analytics Art can check this in your property for you.
Tracking Page Views In A Single-Page App
A React app is a single-page application (SPA): the HTML loads once and JavaScript, often React Router, rewrites the URL. GA4 offers two ways to turn those route changes into page_view events, and you must choose one to avoid double counting, as described in Google's SPA measurement guide.
Option A: Automatic history-based tracking (easiest)
The Google tag can listen for browser history changes (pushState and replaceState) and fire page views automatically. To enable it:
- Open Google Analytics > Admin.
- Under Data collection and modification, click Data streams > your web stream.
- Click the gear icon next to Enhanced measurement.
- Under Page views, click Show advanced settings and enable Page changes based on browser history events alongside Page loads.
- Save.
Now simply initialise react-ga4; no extra code is needed. Every route change triggers a new page_view event with the correct page location and referrer.
Option B: Manual pageview calls
If you need to control the page path or title, disable the automatic history detection (uncheck the box from Option A) and send pageviews yourself with ReactGA.send. React Router’s useLocation hook notifies you of URL changes:
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
const location = useLocation();
useEffect(() => {
ReactGA.send({
hitType: "pageview",
page: location.pathname + location.search,
title: document.title
});
}, [location]);The page field sets a custom path and title a custom title, as in the readme example. Google's SPA guide stresses getting the page referrer right for each virtual page, so check it in DebugView.
Additional SPA Considerations
After every virtual page transition, reset the scroll position so users see the top of the new content and scroll tracking works correctly: add window.scrollTo(0, 0) (or for a specific container, document.getElementById('main-content').scrollTo(0, 0)) in the useEffect that sends the pageview. Also make sure your framework completely updates the DOM before the pageview fires; partial rendering can break on-page search (Ctrl+F) for users. Test search after route changes to confirm content accessibility.
Sending Custom Events
Once GA4 is initialised you can send any custom event using the ReactGA.event method. The package supports two signatures, summarised below.
| Signature | Params | Usage |
|---|---|---|
| GA4-native | name (string), params (object optional) | Recommended for new implementations. Maps directly to gtag('event', name, params). Example: ReactGA.event("sign_up", { method: "email" }). Any recommended or custom event name is allowed. |
| Legacy UA-style | options object with action (required), category (required), label, value, nonInteraction, transport (all optional except the first two) | Only for code migrated from Universal Analytics. Not advised for new GA4 work. Example: ReactGA.event({ category: "Video", action: "Play", label: "Promo", value: 1, nonInteraction: true, transport: "xhr" }). The value must be a number; nonInteraction is an optional true/false flag; transport accepts 'beacon', 'xhr' or 'image'. |
Prefer the GA4-native signature. If you need to issue a command not covered by the wrapper, call ReactGA.gtag(...) directly. For example, ReactGA.gtag("event", "purchase", { … }) is equivalent to the native call. The ReactGA.set method takes a fields object.
Consent And Testing
By default, react-ga4 loads the gtag.js library and begins sending data as if full consent is granted. To comply with privacy regulations, set up Google Consent Mode so that tags adapt based on user choices. Consent Mode documentation explains that tags with built-in checks, including GA4, will respect consent states such as analytics_storage and ad_storage.
Set a default consent state
The recommended implementation (advanced mode) loads tags but sends cookieless pings when consent is denied. To set a default denied state before react-ga4 fires, place the following snippet in public/index.html ahead of any other scripts:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('consent', 'default', {
'analytics_storage': 'denied',
'ad_storage': 'denied'
});
</script>This makes sure that even before React boots the tags know the default state. Later you can update consent via your Consent Management Platform or by calling ReactGA.gtag("consent", "update", { ... }). Read more about Consent Mode V2.
Testing your setup
The react-ga4 readme still points to the Google Analytics Debugger Chrome extension, but Chrome now lists it as deprecated. Instead, enable debug mode for your own device with Google Tag Assistant, which adds a debug parameter to your site's address, and open your React app. Then go to GA4 > Admin > Data display > DebugView. page_location values match the URLs you expect. If you use Tag Manager, you can also verify tags with the Google Tag Assistant.
Frequently Asked Questions
What Is The GA4 Measurement ID And Where Do I Find It?
The measurement ID is a string like G-123ABC that identifies your data stream. Find it in Google Analytics under Admin > Data collection and modification > Data streams, click your web stream, and look for Measurement ID at the top of the stream details.
How Do I Track Page Views In A React App With React Router?
You can let GA4 automatically detect browser history changes by enabling 'Page changes based on browser history events' in enhanced measurement, or manually call ReactGA.send({hitType:'pageview', page:path}) inside a useEffect that watches useLocation. Use one method only to prevent duplicate pageviews.
Can I Use react-ga4 To Send Old Universal Analytics Style Events?
Yes. The ReactGA.event({category, action, label, value}) signature still works for compatibility, but it is not the recommended approach for GA4. Prefer the ReactGA.event(name, params) form to send GA4 events with clean parameters.
What Does The nonInteraction Parameter Do?
It is an optional true/false flag in the legacy, Universal Analytics style ReactGA.event(options) call. The react-ga4 readme documents only its type, not a default or its effect in GA4 reports, so prefer the GA4-native event(name, params) form for new work.
How Can I See Events In Real Time During Development?
Enable debug mode for your device with Google Tag Assistant (tagassistant.google.com), then open DebugView in GA4 (Admin > Data display > DebugView). As you click through your React app, every page_view and custom event appears instantly.
How Do I Initialise react-ga4 With Several GA4 Properties?
Pass an array of objects to ReactGA.initialize. Each object must have a trackingId property and may include optional gaOptions and gtagOptions. The library will send hits to all configured measurement IDs.
Related GA4 Guides
- The GA4 API Explained: Data, Admin And Measurement ProtocolThe GA4 API includes Data API, Admin API, and Measurement Protocol to pull reports, manage settings, and send server-side events. Learn how to get started.
- The Google Analytics MCP Server: Query GA4 From Claude And Other AI ToolsUse the official Google Analytics MCP server to ask GA4 questions in Claude, Gemini, or Cursor. Setup steps, read-only access, and quota limits explained.
- GA4 Measurement Protocol: Send Events From Your ServerUse the GA4 Measurement Protocol to send events from your server, create an API secret, build a request, validate with debug, and understand its limits.
- How To Connect GA4 To Looker StudioConnect GA4 to Looker Studio and build a custom dashboard for Google Analytics. Step-by-step guide to data sources, reports, templates, and quota limits.
- How To Export GA4 Data To BigQueryExport raw GA4 events to BigQuery for SQL analysis. Learn to link properties, choose daily or streaming export, understand the schema, and run your first queries.
More in APIs & Integrations or browse all GA4 guides.