Created
April 20, 2020 14:58
-
-
Save sibelius/9933eeb914cefe99ec014327adf01ee5 to your computer and use it in GitHub Desktop.
usePageView using react-ga
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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