How to use react-ga to track your React website traffic (2020)

February 5, 2020 Goodman Loading... Post a comment

This tutorial shows you how to track your React app (or website) traffic with Google Analytics.

Prerequisites

  • A Google Analytics account
  • Basic React knowledge

Installation

npm install react-ga --save

Code

Create a file and call it MyGa.js:

import ReactGA from 'react-ga';

const myGa = () => {
    const GA_ID = 'UA-000000-01'; // your google analytics id
    ReactGA.initialize(GA_ID);
    ReactGA.pageview(window.location.pathname + window.location.search);
};

export default myGa;

Usage

Simple way:

import React from 'react';
import myGa from './MyGa';

const MyComponent = () => {
    myGa();
   // other code here
};

export default MyComponent;

Using with Effect Hook:

import React, { useEffect } from 'react';
import myGa from './myGa';

const MyPage = () => {
    useEffect(() => {
        myGa();
    }, []);
}

export default MyPage;

Now check your work 🙂 (Note that it will work even on localhost environment).

avatar

Related Articles