Created
March 15, 2022 15:45
-
-
Save jsmolina/80312157f95b2b24fe06a38a17f2dea5 to your computer and use it in GitHub Desktop.
React snippet for tracking user enters or leaves a page
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
const [lastVisit, setLastVisit] = useState(null); | |
useEffect( | |
() => | |
history.listen((e) => { | |
logEvent(TrackEvents.PAGE_VISIT, { route: e.pathname }); | |
const now = Date.now() / 1000; | |
lastVisit && | |
logEvent(TrackEvents.PAGE_LEAVE, { | |
route: lastVisit.path, | |
time: now - lastVisit.visited, | |
}); | |
setLastVisit({ path: e.pathname, visited: now }); | |
}), | |
[lastVisit, history] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment