Welcome to IT Leader Assistant!
Please Log In!

Create an account

How to set up Google Analytics on a React project

Aleksandra Shalamova
11-18-2020 15:09
How to set up Google Analytics on a React project

Google Analytics set up

Google Analytics is essential to the project. It shows not only the number of site visits and which pages are visited, but it also helps us understand the parameters that enable us to adapt the project according to the users' reaction. In this article, I want to tell you how to set up Google Analytics on a React project and what nuances should be considered. 
Setting up Google Analytics is very simple. You just need to insert this tag in the head of your HTML page:
The defer attribute is not incidental here. It is one of the first nuances that you will encounter if you monitor your site's performance, for example, through PageSpeed Insights. Without defer and even with the async attribute, the analytics script's execution will affect the time until your site becomes available to the user. Therefore, this is worth paying attention to.
Further, as indicated in the official documentation, we set up the analytics with the following inline script, also using defer:
<script defer>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', YOUR_PROJECT_ID);
After that, the analytics will start working, and you can track the traffic to your site.

Transitions between React Router pages

If you use React Router in your project, here comes the next nuance. Google Analytics, by default, does not recognize transitions between React Router pages. So, in your statistics, traffic will always consist of one page. To correct this, subscribe to router events and send the data to the analytics manually when changing the page. For convenience, you can create a React component and add it to your application. Example:
import React from 'react';
import { withRouter } from 'react-router-dom';
class GoogleAnalytics extends React.Component {
    componentWillUpdate ({ location, history }) {
        const gtag = window.gtag;
        if (location.pathname === this.props.location.pathname) {
        if (history.action === 'PUSH' &&
            typeof(gtag) === 'function') {
            gtag('config', 'UA-87269926-3', {
                'page_title': document.title,
                'page_location': window.location.href,
                'page_path': location.pathname
    render () {
        return null;
export default withRouter(GoogleAnalytics);
Your statistics will now show the exact number of pages visited by your users.

Using events

I also suggest using events to understand the users' actions, where they go on the site, and where they do not. I made the following wrapper for myself to use in any convenient place in the code:
export const sendMetrik = (action, category, label, value) => {
    const values = {};
    if (typeof category !== 'undefined') {
        values['event_category'] = category;
    if (typeof label !== 'undefined') {
        values['event_label'] = label;
    if (typeof value !== 'undefined') {
        values['value'] = value;
    if (typeof window !== 'undefined' && typeof window.gtag !== 'undefined') {
        window.gtag('event', action, values);
    } else {
	  // на случай, если локально статистика отключена
        console.log('event', action, values);

Elements' visibility

Another useful life hack is the react-visibility-sensor module. It allows you to track the visibility of certain blocks and is often very useful for analyzing user behavior on your site. For example, you added a block at the bottom of the page and want to know how many people saw it and correlate it with the number of people who clicked on a particular button in it. This module will help you with this. An example of its use:
<VisibilitySensor partialVisibility onChange={(isVisible) => {
    if (!this.state.metrikSended && isVisible) {
            metrikSended: true
        sendMetrik('show', this.props.metrik)
    // ваш контент
Sometimes a user might scroll a page several times, thus affecting the following analytics. In this case, it is essential to eliminate the chance of sending duplicated statistics.
These are all the Google Analytics in a React project life hacks that I wanted to share with you today. It is more than enough for a start, and after that, everything will depend on your goals.
If you have any questions or comments, you can use the feedback form to contact us:


To add a comment please log in

Stay tuned and subsribe

Last blog articles