0

I've followed what appear to be fairly boilerplate instructions for using React-GA with React Router by listening on the history object for a change of location. Here's the snippet:

if (process.env.NODE_ENV === 'production') {
    history.listen(location => {
      if (location.pathname.includes('/app')) {
        ReactGA.set({ page: location.pathname }, ['appTracker']); // Update the user's current page
        ReactGA.pageview(location.pathname, ['appTracker']); // Record a pageview for the given page
      } else {
        ReactGA.set({ page: location.pathname }, ['marketingTracker']); // Update the user's current page
        ReactGA.pageview(location.pathname, ['marketingTracker']); // Record a pageview for the given page
      }
    });
  }

The problem is every time the location changes, it sends increasing numbers of hits. So if I start at /login it will send 1 hit. Then I change to /signup and it sends 2 hits on /signup. Then I go back to login and it sends 3 hits to /login. And so on. This appears to possibly be an issue with the history object passed down by BrowserRouter, because the same thing happens for console logs. Like I mentioned, the snippet above was copy/pasted almost verbatim from several other blogs referencing standard setup of React GA with React Router, so I'm not sure how to prevent it from sending these duplicate hits.

ipenguin67
  • 1,483
  • 5
  • 22
  • 39

1 Answers1

0

Found a better way to do this with the useLocation() hook in React Router 5.1^:

App.js:

let location = useLocation();
  useEffect(() => {
    if (process.env.NODE_ENV === 'production') {
      if (location.pathname.includes('/app')) {
        ReactGA.set({ page: location.pathname }, ['appTracker']); // Update the user's current page
        ReactGA.pageview(location.pathname, ['appTracker']); // Record a pageview for the given page
      } else {
        ReactGA.set({ page: location.pathname }, ['marketingTracker']); // Update the user's current page
        ReactGA.pageview(location.pathname, ['marketingTracker']); // Record a pageview for the given page
      }
    }
  }, [location]);
ipenguin67
  • 1,483
  • 5
  • 22
  • 39