How to Implement Google Analytics in React
Adding Google Analytics to your React application is one of the best ways to understand how users are interacting with your site. Because React is a bit different from traditional websites, setup requires a few extra steps. This article will guide you through exactly how to implement Google Analytics in React, from the simplest method to a more robust approach for tracking user navigation and custom events.
First, Get Your GA4 Measurement ID
Before you can add any code, you need a Google Analytics 4 property set up for your website. If you already have one, you can skip to the dedicated section. If not, here’s how to create one and find your all-important Measurement ID.
- Navigate to the Google Analytics homepage and sign in.
- Click the gear icon for "Admin" in the bottom-left corner.
- In the "Property" column, click "Create Property".
- Enter a name for your property (e.g., "My React App"), select your reporting time zone and currency, then click "Next."
- Answer the optional questions about your business and click "Create."
- You'll be prompted to set up a data stream. Choose "Web" as your platform.
- Enter your website's URL and give the stream a name. Then, click "Create stream."
Once you’ve created the stream, a page with your stream details will appear. The key piece of information you need is the Measurement ID, which will be in the format G-XXXXXXXXXX. Copy this ID – you'll need it in the following steps.
Method 1: The Simple Script Tag Approach
The fastest way to get Google Analytics running is by placing the global site tag (gtag.js) directly into your main HTML file. This method is straightforward but has a significant limitation in the context of React applications.
How to Add the Script Tag
In a standard React project (created with Create React App or Vite), you will find an index.html file inside the public folder. This file is the main entry point for your entire application.
- Open the
public/index.htmlfile in your code editor. - Find the closing
</head>tag. - Paste your entire global site tag snippet, which you can get from your GA4 Data Stream settings, right before the closing
</head>tag. Make sure you replaceG-XXXXXXXXXXwith your actual Measurement ID.
Your index.html head should look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [],
function gtag(){dataLayer.push(arguments),}
gtag('js', new Date()),
gtag('config', 'G-XXXXXXXXXX'),
</script>
<title>My React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>The Big Limitation of This Method
While easy, this approach will only track the initial page load. React applications are Single Page Applications (SPAs). This means that when a user navigates from /home to /about, the page content changes dynamically without a full browser refresh. Because the page doesn't reload, the Google Analytics script doesn’t fire again, and your analytics will miss all subsequent page views. This method is only suitable if your app is a literal single page without internal navigation.
Method 2: Using react-ga4 for SPAs (The Recommended Way)
To accurately track page views and custom events in a modern React application, using a dedicated library is the best practice. react-ga4 is a popular and well-maintained package that makes integrating with Google Analytics 4 a breeze.
Step 1: Install react-ga4
First, add the package to your project using npm or yarn. Open your terminal in the project's root directory and run:
npm install react-ga4Step 2: Initialize Google Analytics in Your App
You need to initialize the library with your Measurement ID as soon as your app loads. The ideal place for this is your root component, which is typically App.js or index.js.
It's also a best practice not to hardcode your Measurement ID directly in your code. Using an environment variable is much safer and more flexible. Create a file named .env in your project's root directory and add your ID:
REACT_APP_GA_MEASUREMENT_ID=G-XXXXXXXXXXNow, in your App.js file, you can import react-ga4 and initialize it:
import ReactGA from "react-ga4",
const GA_MEASUREMENT_ID = process.env.REACT_APP_GA_MEASUREMENT_ID,
// Initialize GA
// We do this check because we don't want to track during development
if (process.env.NODE_ENV === "production") {
ReactGA.initialize(GA_MEASUREMENT_ID),
}Wrapping the initialization in a check for the production environment is a great practice. This prevents analytics data from your local development server from appearing in your reports.
Step 3: Track Page Views on Route Changes
This is the most critical step for an SPA. You need to tell Google Analytics to log a page view every time the user navigates to a new page. If you're using React Router, you can create a small, reusable component that listens for location changes and sends the data to GA.
Create a new component file, for example, components/RouteChangeTracker.js:
import { useEffect, useState } from "react",
import { useLocation } from "react-router-dom",
import ReactGA from "react-ga4",
const RouteChangeTracker = () => {
const location = useLocation(),
const [initialized, setInitialized] = useState(false),
useEffect(() => {
// Only initialize if the GA ID is available and we're in production
if (
process.env.REACT_APP_GA_MEASUREMENT_ID &&
process.env.NODE_ENV === "production"
) {
ReactGA.initialize(process.env.REACT_APP_GA_MEASUREMENT_ID),
setInitialized(true),
}
}, []),
useEffect(() => {
// If initialized, fire a pageview every time the location changes
if (initialized) {
ReactGA.send({ hitType: "pageview", page: location.pathname + location.search }),
}
}, [initialized, location]),
return null, // This component doesn't render anything
},
export default RouteChangeTracker,This component uses the useLocation hook from react-router-dom to detect route changes. The useEffect hook triggers every time the location object changes, sending a pageview to GA.
Now, import and include this tracker component within your BrowserRouter in App.js:
import { BrowserRouter as Router, Routes, Route } from "react-router-dom",
import RouteChangeTracker from './components/RouteChangeTracker',
// ... other imports for your pages
function App() {
return (
<Router>
<RouteChangeTracker />
<Navbar />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/contact" element={<ContactPage />} />
</Routes>
</Router>
),
}
export default App,With this setup, every navigation will be correctly logged as a separate page view in Google Analytics.
Step 4: Track Custom Events
Beyond page views, you'll often want to track specific user interactions like button clicks, form submissions, or downloads. These are called events.
The react-ga4 library makes this easy with the ReactGA.event() method. Let's say you have a pricing page and want to track a click on the "Sign Up Now" button.
PricingPage.js component:
import React from 'react',
import ReactGA from "react-ga4",
const PricingPage = () => {
const handleSignUpClick = (plan) => {
ReactGA.event({
category: "Conversion",
action: "Clicked Sign Up Button",
label: `${plan} Plan`, // E.g., 'Pro Plan'
}),
// ... add your normal sign up logic here
},
return (
<div>
<h1>Our Pricing</h1>
{/* ... your pricing table content ... */}
<button onClick={() => handleSignUpClick('Pro Plan')}>
Sign Up Now
</button>
</div>
),
},
export default PricingPage,In this example, every time the button is clicked, an event with the category "Conversion", action "Clicked Sign Up Button", and a dynamic label for the specific plan is sent to Google Analytics. This gives you granular data on which pricing plans are most popular.
How to Verify Your Implementation is Working
After implementing the code, you need to confirm that data is being sent correctly to Google Analytics.
- Use the Realtime Report: The easiest way is to open your app in the browser and navigate to a few pages while having the "Reports" > "Realtime" view open in your GA4 dashboard. You should see your own activity appear within a minute or two.
- Use Browser Developer Tools: Open your browser's DevTools and go to the "Network" tab. In the filter box, type
collect. Now, as you navigate your site and click on tracked elements, you should see network requests being made togoogle-analytics.com/g/collect.... This confirms that your app is sending the data. - Use GA DebugView: For more detailed debugging, install the Google Analytics Debugger Chrome extension. When enabled, your events will show up in detail within the "Admin" > "DebugView" section of your GA property, which is incredibly useful for troubleshooting.
Final Thoughts
Integrating Google Analytics into a React app goes beyond a simple copy-paste of a script. By using a library like react-ga4 and a route change hook, you can ensure accurate data collection that reflects how users truly navigate and interact with your single page application, allowing you to track both page views and important custom events.
Once you have all this valuable user data flowing into Google Analytics, the next challenge is transforming it into clear, actionable reports. Instead of spending hours manually building dashboards or getting lost in the GA4 interface, we built Graphed to do the heavy lifting for you. We allow you to connect your Google Analytics account in seconds and then use simple, natural language - like "Show me top landing pages by sessions for the last 30 days" - to instantly create the real-time dashboards and insights you need.
Related Articles
How to Connect Facebook to Google Data Studio: The Complete Guide for 2026
Connecting Facebook Ads to Google Data Studio (now called Looker Studio) has become essential for digital marketers who want to create comprehensive, visually appealing reports that go beyond the basic analytics provided by Facebook's native Ads Manager. If you're struggling with fragmented reporting across multiple platforms or spending too much time manually exporting data, this guide will show you exactly how to streamline your Facebook advertising analytics.
Appsflyer vs Mixpanel: Complete 2026 Comparison Guide
The difference between AppsFlyer and Mixpanel isn't just about features—it's about understanding two fundamentally different approaches to data that can make or break your growth strategy. One tracks how users find you, the other reveals what they do once they arrive. Most companies need insights from both worlds, but knowing where to start can save you months of implementation headaches and thousands in wasted budget.
DashThis vs AgencyAnalytics: The Ultimate Comparison Guide for Marketing Agencies
When it comes to choosing the right marketing reporting platform, agencies often find themselves torn between two industry leaders: DashThis and AgencyAnalytics. Both platforms promise to streamline reporting, save time, and impress clients with stunning visualizations. But which one truly delivers on these promises?