Setting up a custom hook for connecting Google Analytics to React app

Setting up a custom hook for connecting Google Analytics to React app

Google Analytics is a web analytics service offered by Google that tracks and reports website traffic. They offer a great dashboard and the service is free. Our goal is to connect the Google Analytics to our React app using some utility functions and a custom React hook that handles the initialization of the ga object.

Prerequisites

  • A Google Analytics account

  • A property set up in your Google Analytics account, with a tracking ID (e.g. UA-12345678-1)

Install the react-ga library

Run the following command in your terminal to install the react-ga library:

npm install react-ga

Create the custom hook

Create a new file in your React project called useGoogleAnalytics.js and add the following code:

import React from 'react'; import ReactGA from 'react-ga'; export default functionuseGoogleAnalytics(trackingId) { React.useEffect(() => { ReactGA.initialize(trackingId); }, [trackingId]); function trackPageView(page) { ReactGA.set({ page });ReactGA.pageview(page); } return { trackPageView }; }

This custom hook uses the useEffect hook to initialize the Google Analytics tracking code with your tracking ID when the component mounts. It also has a trackPageView function that you can use to track page views in your app.

Use the custom hook in your app

To use this hook in your app, import it and use it like any other hook. For example, if you want to track page views in your App component, you can do the following:

import React from 'react'; import useGoogleAnalytics from './useGoogleAnalytics';function App() { const { trackPageView } = useGoogleAnalytics('UA-12345678-1');React.useEffect(() => { trackPageView(window.location.pathname); }, []); return ( <div>{/* Your app code here */} </div> ); } export default App;

This will track page views whenever the App component mounts or updates. You can also call the trackPageView function manually whenever you want to track a page view, for example when the user clicks a link or button.

Conclusion

That's it! You should now be able to track page views in your React app using Google Analytics.