How To Add Google Analytics In React Js

If you are using React JS for your web development, incorporating Google Analytics may seem daunting. However, fear not! This blog post will guide you through the process of integrating Google Analytics into your React JS application, a crucial tool for evaluating website success and understanding user behavior.

Step 1: Obtain Your Google Analytics Tracking ID

Firstly, you need to have a Google Analytics Tracking ID. If you don’t have one, you can create it on the Google Analytics website. Remember to keep this ID handy, we will be needing it in the upcoming steps.

Step 2: Install the React-GA Library

The react-ga library is very useful for integrating Google Analytics with a React JS application. It provides a simple and straightforward way to add Google Analytics’ tracking code. You can add it to your project by running the following command in your project directory:

npm install react-ga

Step 3: Initialize React-GA in Your Application

Once you have installed the react-ga library, you need to initialize it in your application. You can do this by importing the library in your main application file (usually App.js) and then using the initialize function from the library, passing in your Google Analytics Tracking ID:

import ReactGA from 'react-ga';


Step 4: Tracking Pageviews

Now that you have initialized Google Analytics, you can start tracking pageviews. This can be done using the pageview function. This function should be called whenever a new page is loaded. Here is an example of how you can do this in the componentDidMount lifecycle method of your main application component:

componentDidMount() {
  ReactGA.pageview(window.location.pathname +;

Step 5: Tracking Events

Google Analytics not only allows you to track pageviews, but also user interactions with your website. This includes tracking clicks on buttons, form submissions, and more. You can track these events using the event function from the react-ga library:

  category: 'User',
  action: 'Clicked Button'

And that’s it! You have successfully added Google Analytics to your React JS application. Remember, the key to making the most out of Google Analytics is to constantly track and analyze your data. This will allow you to understand your users’ behaviour and improve your website accordingly. Happy tracking!