{"id":15185,"library":"react-ga4","title":"React Google Analytics 4 Wrapper","description":"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.","status":"active","version":"3.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/codler/react-ga4","tags":["javascript","GA","GTM","Google Analytics","Google Analytics 4","Google Tag Manager","typescript"],"install":[{"cmd":"npm install react-ga4","lang":"bash","label":"npm"},{"cmd":"yarn add react-ga4","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-ga4","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Since v3.0.1, react-ga4 is an ESM-only module. CommonJS `require()` is no longer supported.","wrong":"const ReactGA = require('react-ga4');","symbol":"ReactGA","correct":"import ReactGA from 'react-ga4';"},{"note":"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.","symbol":"initialize","correct":"import ReactGA from 'react-ga4';\nReactGA.initialize('G-MEASUREMENT_ID');"},{"note":"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.","wrong":"ReactGA.pageview('/my-custom-path');","symbol":"send (pageview)","correct":"import ReactGA from 'react-ga4';\nReactGA.send({ hitType: 'pageview', page: '/my-custom-path', title: 'Custom Page Title' });"},{"note":"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.","wrong":"ReactGA.event('Video', 'play', 'My Video', 100);","symbol":"event","correct":"import ReactGA from 'react-ga4';\nReactGA.event({ category: 'Video', action: 'play', label: 'My Video', value: 100 });"}],"quickstart":{"code":"import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport ReactGA from 'react-ga4';\n\n// Replace 'G-YOUR_MEASUREMENT_ID' with your actual GA4 Measurement ID\nconst GA_MEASUREMENT_ID = process.env.REACT_APP_GA_MEASUREMENT_ID ?? 'G-YOUR_MEASUREMENT_ID';\n\nif (GA_MEASUREMENT_ID) {\n  ReactGA.initialize(GA_MEASUREMENT_ID, {\n    testMode: process.env.NODE_ENV === 'development' // Optional: enable test mode in development\n  });\n  console.log('Google Analytics 4 initialized with ID:', GA_MEASUREMENT_ID);\n} else {\n  console.warn('Google Analytics 4 Measurement ID not found. GA will not be initialized.');\n}\n\nfunction App() {\n  React.useEffect(() => {\n    // Send an initial pageview when the component mounts\n    // Note: ReactGA sends a default pageview on initialize, but this shows manual control.\n    ReactGA.send({ hitType: 'pageview', page: window.location.pathname + window.location.search, title: document.title });\n\n    const handleButtonClick = () => {\n      ReactGA.event({\n        category: 'User Interaction',\n        action: 'Click',\n        label: 'Submit Button',\n        value: 1\n      });\n      console.log('GA4 event sent: Submit Button Click');\n    };\n\n    // Simulate a route change after 2 seconds\n    const timeoutId = setTimeout(() => {\n      const newPath = '/dashboard';\n      ReactGA.send({ hitType: 'pageview', page: newPath, title: 'Dashboard Page' });\n      console.log('GA4 pageview sent for:', newPath);\n    }, 2000);\n\n    return () => clearTimeout(timeoutId);\n\n  }, []);\n\n  return (\n    <div>\n      <h1>Welcome to the React GA4 Example!</h1>\n      <p>Check your browser's network tab or GA4 debug view for tracking events.</p>\n      <button onClick={handleButtonClick}>Send Custom Event</button>\n    </div>\n  );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<App />);","lang":"typescript","description":"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."},"warnings":[{"fix":"Migrate your import statements from `const ReactGA = require('react-ga4');` to `import ReactGA from 'react-ga4';`","message":"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.","severity":"breaking","affected_versions":">=3.0.1"},{"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.","message":"Version 2.0.0 removed the deprecated `pageview`, `outboundLink`, and `legacyDimensionMetric` methods. Explicit calls to `ReactGA.pageview()` will result in an error.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Ensure you are passing an object to `ReactGA.event()`, e.g., `ReactGA.event({ category: 'Video', action: 'Play' });` instead of `ReactGA.event('Video', 'Play');`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Change your import statement from `const ReactGA = require('react-ga4');` to `import ReactGA from 'react-ga4';`.","cause":"Attempting to import `react-ga4` using CommonJS `require()` syntax in a project configured for ES Modules, or after upgrading to v3.0.1+.","error":"ReferenceError: require is not defined"},{"fix":"Replace `ReactGA.pageview('/some-path');` with `ReactGA.send({ hitType: 'pageview', page: '/some-path' });`.","cause":"Attempting to use the `pageview` method after upgrading to `react-ga4` v2.0.0 or later, where this method was removed.","error":"TypeError: ReactGA.pageview is not a function"},{"fix":"Ensure the object passed to `ReactGA.event()` includes both `category` and `action` properties, for example: `ReactGA.event({ category: 'UI', action: 'ButtonClick', label: 'Submit' });`.","cause":"Attempting to send a GA4 event with an incorrect object structure or missing required `category` and `action` properties.","error":"Google Analytics event 'your action' has no 'category' and 'action' attributes."}],"ecosystem":"npm"}