How to set up Google Analytics for React Router?

Sometimes, we want to set up Google Analytics for React Router.

In this article, we’ll look at how to set up Google Analytics for React Router.

How to set up Google Analytics for React Router?

To set up Google Analytics for React Router, we can create our own hook to submit data to Google Analytics.

For instance, we write

import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";

const usePageTracking = () => {
  const location = useLocation();

  useEffect(() => {
    ReactGA.initialize("UA-000000000-0");
    ReactGA.pageview(location.pathname + location.search);
  }, [location]);
};

export default usePageTracking;

to create the usePageTracking hook that calls the useLocation hook to get the current location.

And then we listen to location with the useEffect hook and calls ReactGA.initialize to initialize Google Analytics.

And then we call ReactGA.pageview with the full URL which we get with location.pathname + location.search.

Conclusion

To set up Google Analytics for React Router, we can create our own hook to submit data to Google Analytics.