Registry / observability / react-ga4

react-ga4

JSON →
library3.0.1jsnpmunverified

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.

npm install react-ga4
INSTALL
IMPORT
SIG · REACT-GA4
R
react-ga4
observabilityjavascriptv3.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ReactGA
import ReactGA from 'react-ga4';
const ReactGA = require('react-ga4');
Since v3.0.1, react-ga4 is an ESM-only module. CommonJS `require()` is no longer supported.
initialize
import ReactGA from 'react-ga4'; ReactGA.initialize('G-MEASUREMENT_ID');
The `initialize` method is the primary entry point for configuring GA4 with your Measurement ID. It can be called with a single ID or an array of objects for multiple trackers.
send (pageview)
import ReactGA from 'react-ga4'; ReactGA.send({ hitType: 'pageview', page: '/my-custom-path', title: 'Custom Page Title' });
ReactGA.pageview('/my-custom-path');
The `pageview` method was removed in v2.0.0. Use `ReactGA.send({ hitType: 'pageview', ... })` for custom page views. Default page views are sent automatically upon initialization.
event
import ReactGA from 'react-ga4'; ReactGA.event({ category: 'Video', action: 'play', label: 'My Video', value: 100 });
ReactGA.event('Video', 'play', 'My Video', 100);
For GA4, the `event` method expects an object with `category`, `action`, and optionally `label`, `value`, etc. The old positional arguments are not supported for GA4.

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 />);
Debug
Known issues
breakingVersion 3.0.1 and later are ESM-only modules. This means `require()` statements for importing `react-ga4` will fail. You must use ES module `import` syntax.
fix
Migrate your import statements from `const ReactGA = require('react-ga4');` to `import ReactGA from 'react-ga4';`
affects: >=3.0.1
breakingVersion 2.0.0 removed the deprecated `pageview`, `outboundLink`, and `legacyDimensionMetric` methods. Explicit calls to `ReactGA.pageview()` will result in an error.
fix
Remove `ReactGA.pageview()` calls. To send custom page views, use `ReactGA.send({ hitType: 'pageview', page: '/my-path' });`. Note that page views are sent by default upon initialization and route changes if not explicitly disabled.
affects: >=2.0.0
gotchaThe `ReactGA.event()` method signature for Google Analytics 4 is different from Universal Analytics. It expects an object with properties like `category`, `action`, `label`, `value`, etc., rather than positional arguments.
fix
Ensure you are passing an object to `ReactGA.event()`, e.g., `ReactGA.event({ category: 'Video', action: 'Play' });` instead of `ReactGA.event('Video', 'Play');`.
affects: >=1.0.0
gotchaBy default, `react-ga4` sends a page view upon `initialize()`. If you are manually sending page views (e.g., within a React Router `useEffect`), you may end up with duplicate page views if not handled carefully.
fix
Consider disabling the default page view sending during initialization or ensure your manual page view logic accounts for this. If you are using a router, you might typically send page views on route changes rather than on initial load.
affects: >=2.0.0
Errors
Common errors & fixes
ReferenceError: require is not defined
Attempting to import `react-ga4` using CommonJS `require()` syntax in a project configured for ES Modules, or after upgrading to v3.0.1+.
fix
Change your import statement from `const ReactGA = require('react-ga4');` to `import ReactGA from 'react-ga4';`.
TypeError: ReactGA.pageview is not a function
Attempting to use the `pageview` method after upgrading to `react-ga4` v2.0.0 or later, where this method was removed.
fix
Replace `ReactGA.pageview('/some-path');` with `ReactGA.send({ hitType: 'pageview', page: '/some-path' });`.
Google Analytics event 'your action' has no 'category' and 'action' attributes.
Attempting to send a GA4 event with an incorrect object structure or missing required `category` and `action` properties.
fix
Ensure the object passed to `ReactGA.event()` includes both `category` and `action` properties, for example: `ReactGA.event({ category: 'UI', action: 'ButtonClick', label: 'Submit' });`.
Upgrade
Version history
3.0.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
16 hits · last 30 days
node
14
OpenAI (training)
2
Resources
react-ga4 — npm install react-ga4 · libregistry