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.