I\'m trying set up Google Analytics on my react site, and have come across a few packages, but none of which has the kind of set up that I have in terms of examples. Was ho
Since react-router v5.1.0 this can be solved a lot easier with useLocation.
usePageTracking.js
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;
App.js
const App = () => {
usePageTracking();
return (...);
};
See also:
Here's a bit smarter version:
usePageTracking.js
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";
const usePageTracking = () => {
const location = useLocation();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if (!window.location.href.includes("localhost")) {
ReactGA.initialize("UA-000000000-0");
}
setInitialized(true);
}, []);
useEffect(() => {
if (initialized) {
ReactGA.pageview(location.pathname + location.search);
}
}, [initialized, location]);
};
export default usePageTracking;