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';

ReactGA.initialize('UA-#########-#');

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) => 
 ReactGA.pageview(pageName);

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

Using in some component

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

const SomePageComponent = () => {
 useAnalytics('some-page');
 return(...)
}

Tests

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

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

describe('SomePageComponent test', () => {
  beforeEach(() => {
    clearAnalytics();
    ...
  });

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(() => {
    makePageView(pageName);
    return () => getPageTime(pageName);
  }, [pageName]);

Conclusion

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)