Berkay Tayfun Demirbaş
Berkay Tayfun Demirbaş - 04 September 2022
Head of Product Analytics

It is an undeniable fact that React and Google Analytics are one of the most popular tools and libraries among the web-analyst community. Google Analytics is the most widely used web analysis tool, which helps you easily track and retarget your users.

Google Analytics 4 (GA4) provides you with more comprehensive measurement methods such as personalized reports and intelligence analytics, by blending your web and mobile application together. Moreover, it provides you with better insights into your digital marketing strategies compared to Universal Analytics (UA).

Known for being fast and simple, React is the most popular front-end JavaScript library in the field of web development. Using Google Analytics on your React-based website gives you the following benefits:

  • You can find out from which country your users are driving traffic and what demographics they have.
  • You can see how much time your users spend on which pages.
  • You can measure the Enhanced Ecommerce and custom events.
  • You can report bugs in your React application.
  • You can measure user behavior for A/B tests in your application.

Assuming you have a Google Analytics 4 account and a react-based website, let's see how you can set up a healthy react google analytics property step by step.

First of all, you need to create a GA4 property within your current Universal Analytics account. You can use the GA4 Property Setup Assistant for this. Click on Get Started and it will be installed instantly without any pre-configuration.

React & Google Analytics: How to Integrate GA4 in React?

You can see that the GA4 installation was successful from the Connected Property section.

React & Google Analytics: How to Integrate GA4 in React?

Google Analytics 4 Measurement ID

Half of our work is done. Now that we have received the most important part, which is GA4 Measurement ID, which starts with G-, so that you can complete the GA4 installation on our React-based website.

React & Google Analytics: How to Integrate GA4 in React?

React Google Analytics Integration

In the React ecosystem in the digital marketing world, Static Site Generators (SSG) such as Gatsby and NextJS are generally used for page management, plugin support, CMS, site speed, and SEO compatibility concerns.

Now let's start with possible integration methods.

Adding Gtag Script

First you need to install the react-ga package in your application.

yarn add react-ga

Then you have to add the react-ga package into index.js or app.js.

import ReactGA from 'react-ga';
const TRACKING_ID = "UA-12341234-1"; // YOUR_OWN_TRACKING_ID

One of the most common problems in React applications occurs in the rendering methods, specifically, CSR (Client Side Rendering) and SSR (Server Side Rendering). You can access detailed information here for rendering methods.

In your SPA (Single Page Application) applications, you should send your events with history.listen using react-router-dom in order to prevent these rendering problems.

import React from 'react'
import { withRouter } from 'react-router-dom';
import ReactGA from 'react-ga';
const RouteChangeTracker = ({ history }) => {
   history.listen((location, action) => {
       ReactGA.set({ page: location.pathname });
; }; export default withRouter(RouteChangeTracker);

Gatsby GTAG Plugin

If you use Gatsby engine on your website, adding gatsby-plugin-google-gtag /) is recommended.

First of all, you need to install the gatsby-plugin-google-gtag plugin.

yarn add gatsby-plugin-google-gtag

Then you should update the gatsby-config.js file as follows:

module.exports = {
  plugins: [
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        trackingIds: [
          "GA-TRACKING_ID",         ],
        gtagConfig: {
          optimize_id: "OPT_CONTAINER_ID",
          anonymize_ip: true,
          cookie_expires: 0,
        pluginConfig: {
          head: false,
          respectDNT: true,
          exclude: ["/preview/**", "/do-not-track/me/too/"],

Because of the SSR, you may also have to send your custom events as shown below.

typeof window !== "undefined" && window.gtag("event", "click", { })

Adding GTAG Script in Next.js

In the folder where your Next.js application is located, you can open the .env.local file, so that you can add your Measurement ID.


You can easily add this variable in the .env.local file, for example if you are using Vercel.

React & Google Analytics: How to Integrate GA4 in React?

Then it will be enough to add the snippet into the _document.js file.

import Document, { Html, Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
  render() {
    return (

{/* Global Site Tag (gtag.js) - Google Analytics */}

) } }

To pull custom events, you should use this following method;

export const event = ({ action, params }) => {
  window.gtag('event', action, params)

As you can see, there are different Google Analytics 4 integration methods according to different frameworks.

However, no matter what React framework you are using, you must first understand how Google Analytics pulls data from any web application. This will prevent possible measurement and integration errors on your website.

React & Google Analytics: How to Integrate GA4 in React?

You can access the source on how Google Analytics 4 works on the Gtag script here.

Our Similar Articles in The Product Analytics & Data Category

Business Intelligence Reporting: Revolutionizing Digital Marketing Strategies
Business Intelligence Reporting: Revolutionizing Digital Marketing Strategies

Dive into this insightful article to discover how business intelligence reporting can revolutionize your digital marketing strategy, with five transformative ways to harness data-driven insights.

Read more
Importance of Customer Segmentation
Importance of Customer Segmentation

You can easily access a lot of information about customer segmentation, target audience determination, customer analysis by browsing our content.

Read more
Market Basket Analysis
Market Basket Analysis

No need to worry and lose time on searching for what you want, here it is! Give 5 minutes to check out our blog and learn more about the Market Basket Analysis!

Read more
We are waiting for you! Contact us now to meet our multidimensional digital marketing solutions.