DEV Community

Dennis Kaffer
Dennis Kaffer

Posted on

ReactGA Custom Hook

First install ReactGA

npm install react-ga --save

After install, add react-ga in your project, you can do the configuration whatever you want, here is just an example in index.js.

import React from 'react';
import ReactDOM from 'react-dom';
import ReactGA from 'react-ga';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';


ReactDOM.render(<App />, document.getElementById('root'));

The hook code

The hook code folder/file example utils/googleAnalytics.js.

import { useEffect } from 'react';
import ReactGA from 'react-ga';

export const makePageView = (pageName) => 

export const useAnalytics = pageName =>
  useEffect(() => {
  }, [pageName]);

Using in some component

import React from 'react';
import { useAnalytics } from 'utils/googleAnalytics';

const SomePageComponent = () => {


To make sure that your tests don't break, add this clearAnalytics function.

export const clearAnalytics = () => {
  ReactGA.initialize('dummy', { testMode: true });

describe('SomePageComponent test', () => {
  beforeEach(() => {

Why do it that way?

Doing it this way can be a bit more work, but we can have more control and add specific behaviors for the component, for example I would like to make a metric of how long the user stayed on the page, we could put this treatment in the unmount of our hook who will know when the component is unmounted.

export const useAnalytics = pageName =>
  useEffect(() => {
    return () => getPageTime(pageName);
  }, [pageName]);


The possibilities of increasing this hook are almost endless, I demonstrated it this way because I found it simpler, I hope I helped in something.

Top comments (0)