DEV Community

Dennis Kaffer
Dennis Kaffer

Posted on

2

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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️