React Google Analytics 4 Wrapper
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
-
ReferenceError: require is not defined
cause Attempting to import `react-ga4` using CommonJS `require()` syntax in a project configured for ES Modules, or after upgrading to v3.0.1+.fixChange your import statement from `const ReactGA = require('react-ga4');` to `import ReactGA from 'react-ga4';`. -
TypeError: ReactGA.pageview is not a function
cause Attempting to use the `pageview` method after upgrading to `react-ga4` v2.0.0 or later, where this method was removed.fixReplace `ReactGA.pageview('/some-path');` with `ReactGA.send({ hitType: 'pageview', page: '/some-path' });`. -
Google Analytics event 'your action' has no 'category' and 'action' attributes.
cause Attempting to send a GA4 event with an incorrect object structure or missing required `category` and `action` properties.fixEnsure the object passed to `ReactGA.event()` includes both `category` and `action` properties, for example: `ReactGA.event({ category: 'UI', action: 'ButtonClick', label: 'Submit' });`.
Warnings
- breaking Version 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.
- breaking Version 2.0.0 removed the deprecated `pageview`, `outboundLink`, and `legacyDimensionMetric` methods. Explicit calls to `ReactGA.pageview()` will result in an error.
- gotcha The `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.
- gotcha By 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.
Install
-
npm install react-ga4 -
yarn add react-ga4 -
pnpm add react-ga4
Imports
- ReactGA
const ReactGA = require('react-ga4');import ReactGA from 'react-ga4';
- initialize
import ReactGA from 'react-ga4'; ReactGA.initialize('G-MEASUREMENT_ID'); - send (pageview)
ReactGA.pageview('/my-custom-path');import ReactGA from 'react-ga4'; ReactGA.send({ hitType: 'pageview', page: '/my-custom-path', title: 'Custom Page Title' }); - event
ReactGA.event('Video', 'play', 'My Video', 100);import ReactGA from 'react-ga4'; ReactGA.event({ category: 'Video', action: 'play', label: 'My Video', value: 100 });
Quickstart
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 />);