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-ga4Verified import paths — ran on the pinned version, not inferred.
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.
Migrate your import statements from `const ReactGA = require('react-ga4');` to `import ReactGA from 'react-ga4';`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.Ensure you are passing an object to `ReactGA.event()`, e.g., `ReactGA.event({ category: 'Video', action: 'Play' });` instead of `ReactGA.event('Video', 'Play');`.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.
Change your import statement from `const ReactGA = require('react-ga4');` to `import ReactGA from 'react-ga4';`.Replace `ReactGA.pageview('/some-path');` with `ReactGA.send({ hitType: 'pageview', page: '/some-path' });`.Ensure the object passed to `ReactGA.event()` includes both `category` and `action` properties, for example: `ReactGA.event({ category: 'UI', action: 'ButtonClick', label: 'Submit' });`.No dependency data recorded yet.