Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created April 20, 2020 14:58
Show Gist options
  • Save sibelius/9933eeb914cefe99ec014327adf01ee5 to your computer and use it in GitHub Desktop.
Save sibelius/9933eeb914cefe99ec014327adf01ee5 to your computer and use it in GitHub Desktop.
usePageView using react-ga
import { usePrevious } from '@app/hooks';
import { useEffect } from 'react';
import ReactGA from 'react-ga';
import { useLocation } from 'react-router-dom';
export const usePageView = () => {
const location = useLocation();
const lastLocation = usePrevious(location);
useEffect(() => {
const handlePageView = () => {
if (!lastLocation) {
ReactGA.pageview(window.location.pathname + window.location.search);
return;
}
if (lastLocation.pathname !== location.pathname || lastLocation.search !== location.search) {
ReactGA.pageview(window.location.pathname + window.location.search);
}
};
handlePageView();
}, [location]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment