How to Use React Google Analytics 4
Adding Google Analytics 4 to your React application is one of the quickest ways to understand how people actually use what you've built. Without it, you're flying blind, guessing which features are popular and where users are dropping off. This article will walk you through, step-by-step, how to integrate GA4 into your React app to start tracking pageviews and custom events today.
Why Track Analytics in a React App?
Before diving into the code, it's worth remembering why you're doing this. Analytics helps you move from assumption to evidence. By tracking user behavior, you can:
- Understand User Journeys: See the exact paths users take through your app. Which pages do they visit first? Where do they go next? Where do they leave?
- Identify Popular Features: Know which buttons get clicked and which components get the most interaction. This helps you focus your development efforts on what matters most to your users.
- Measure Conversion Rates: Track critical actions, like contact form submissions, free trial sign-ups, or product purchases, to understand how well your app is achieving its goals.
- Find and Fix Usability Issues: By spotting where users get stuck or abandon a task, you can identify parts of your UI/UX that need improvement.
Step 1: Set Up Your Google Analytics 4 Property
You can't track data without a place to send it. Your first step is to create a Google Analytics 4 property if you don't already have one.
- Sign in to Google Analytics: Go to the Google Analytics website and sign in.
- Go to Admin: Click the gear icon in the bottom-left corner to navigate to the Admin page.
- Create a Property: In the 'Property' column, click the "Create Property" button.
- Enter Property Details: Give your property a name (e.g., "My React App"), select your reporting time zone, and choose your currency.
- Set Up a Data Stream: Analytics data is collected via a "Data Stream." Since you're integrating with a website/web app, choose the 'Web' platform.
- Configure Your Web Stream: Enter your application's URL and give the stream a name. Make sure "Enhanced measurement" is turned on - this automatically tracks events like scrolls and outbound clicks.
- Get Your Measurement ID: After creating the stream, you'll see a panel with all the stream details. The most important piece of information here is your Measurement ID. It will look something like
G-XXXXXXXXXX. Copy this ID, you'll need it in the next step.
Step 2: Install and Configure react-ga4
While you can add Google's gtag.js script manually, the easiest and most "React-friendly" way to manage GA4 is with a dedicated library. The react-ga4 package is popular, well-maintained, and simplifies the process significantly.
First, open your terminal, navigate to your React project directory, and install the package:
npm install react-ga4Next, you need to initialize Google Analytics when your app loads. The best place to do this is in your main entry file, which is typically src/index.js or src/App.js.
Using your Measurement ID from the previous step, add the following initialization code:
import ReactGA from "react-ga4",
const GA_MEASUREMENT_ID = "G-XXXXXXXXXX", // taken from GA4 setup
ReactGA.initialize(GA_MEASUREMENT_ID),That's it for the basic setup! react-ga4 is now configured in your project, but it isn't tracking anything just yet. Now let's put it to work.
Step 3: Tracking Pageviews in a Single-Page App
This is the most critical and often misunderstood part of implementing analytics in a React app. By default, Google Analytics tracks a "pageview" when a new web page loads from the server. However, in a Single-Page Application (SPA) like React, users navigate between different "pages" or views without a full page reload. The URL changes, but Google doesn't know it happened.
You need to tell GA4 manually every time the route changes. If you're using React Router, this is thankfully straightforward.
Creating a Component to Track Route Changes
The best way to handle this is by creating a small, reusable component that listens for location changes and sends a pageview event.
Create a new component file, for example, src/components/AnalyticsTracker.js:
import { useEffect, useState } from "react",
import { useLocation } from "react-router-dom",
import ReactGA from "react-ga4",
const AnalyticsTracker = () => {
const location = useLocation(),
const [initialized, setInitialized] = useState(false),
useEffect(() => {
if (process.env.REACT_APP_GA_MEASUREMENT_ID && !initialized) {
ReactGA.initialize(process.env.REACT_APP_GA_MEASUREMENT_ID),
setInitialized(true),
}
}, [initialized]),
useEffect(() => {
if (initialized) {
ReactGA.send({ hitType: "pageview", page: location.pathname + location.search }),
}
}, [initialized, location]),
return null,
},
export default AnalyticsTracker,Note: We added the initialization here as well. It's often cleaner to manage everything related to analytics in a dedicated component. Using an environment variable like REACT_APP_GA_MEASUREMENT_ID is a best practice for storing your Measurement ID.
Now, import and include this component in your App.js file, inside your BrowserRouter tags:
// In your App.js
import React from 'react',
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom',
import AnalyticsTracker from './components/AnalyticsTracker',
// ... other imports for your pages ...
function App() {
return (
<Router>
<AnalyticsTracker />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
{/* ... your other routes ... */}
</Routes>
</Router>
),
}
export default App,With this setup, every time a user navigates to a new route in your app, the useEffect hook in AnalyticsTracker will fire because location has changed, and it will send a pageview event with the correct path to Google Analytics.
Step 4: Tracking Custom Events
Pageviews are good, but the real power of analytics comes from tracking specific user interactions called events. An event can be anything from a button click to a newsletter sign-up or watching a video.
With react-ga4, tracking an event is a one-line command. Let's say you want to track when a user clicks the "Sign Up" button on your homepage.
First, create a simple event handling function in your component:
import ReactGA from 'react-ga4',
const handleSignUpClick = () => {
ReactGA.event({
category: "User",
action: "Clicked Sign Up",
label: "Top Navigation" // optional
}),
},Then, attach this function to your button's onClick handler:
<button onClick={handleSignUpClick}>Sign Up for Free</button>When this button is clicked, react-ga4 will send an event to GA4 with the category, action, and label you defined. This lets you see precisely how many users are engaging with key calls-to-action.
Examples of Common Events to Track:
- Form Submissions:
ReactGA.event({ category: 'Form', action: 'Submitted Contact Form' }), - Product Added to Cart:
ReactGA.event({ category: 'eCommerce', action: 'Added to Cart', label: 'Product Name' }), - File Download:
ReactGA.event({ category: 'Document', action: 'Downloaded PDF', label: 'Case Study 2024' }),
Step 5: Verifying Your Implementation
After implementing your tracking, you need to make sure it's actually working. The best tool for this is Google Analytics' own DebugView.
- Install the Google Analytics Debugger Extension: This is a Chrome extension that forces your browser to send data to GA in debug mode.
- Enable the Extension: Once installed, click its icon in your Chrome toolbar to turn it on for your site. Reload your application page.
- Navigate to DebugView in GA4: In your Google Analytics property, go to Admin > DebugView.
As you navigate your React app and click on buttons you've set up for event tracking, you should see those events appear in the DebugView timeline in near real-time. If you see events like page_view and your custom events, your setup is correct!
Alternative: Manual gtag.js Implementation
If you prefer not to add an extra library to your bundle, you can implement tracking manually using Google's gtag.js script.
- Add the Script to
index.html: Open yourpublic/index.htmlfile and paste thegtag.jsscript provided by Google Analytics in the<head>section. ReplaceG-XXXXXXXXXXwith your Measurement ID. - Create an Analytics Helper: To avoid calling
window.gtageverywhere, create a helper file likesrc/analytics.jsto manage your tracking calls:
// src/analytics.js
export const trackPageView = (path) => {
if (window.gtag) {
window.gtag("config", "G-XXXXXXXXXX", {
page_path: path,
}),
}
},
export const trackEvent = (action, category, label) => {
if (window.gtag) {
window.gtag("event", action, {
event_category: category,
event_label: label,
}),
}
},- Use the Helpers: Now you can import and use these functions. You would call
trackPageViewinside auseEffectthat watches for location changes (just like we did withreact-ga4) and calltrackEventinside youronClickhandlers. While slightly more boilerplate, this method gives you full control and avoids an external dependency.
Final Thoughts
Integrating Google Analytics 4 into your React app empowers you to make data-driven decisions. Using a library like react-ga4 streamlines the process, particularly for handling pageviews in a single-page environment and tracking custom user events. Taking an hour to set this up will pay dividends in the long run by providing you with the insights needed to grow and improve your application.
Of course, setting up tracking is a great first step, but analyzing all that data is where the real value lies. Manually digging through the Google Analytics interface to connect the dots between your campaign sources, website behavior, and conversion events can quickly become a full-time job. We created Graphed to automate that entire process. Just connect your GA account, and you can instantly use natural language to ask questions like "Which traffic sources drove the most sign-ups last month?" or "Create a dashboard showing user engagement by country." We help you get clear answers in seconds, so you can spend less time reporting and more time acting on what you find.
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?