Skip to content

Instantly share code, notes, and snippets.

@jsmolina
Created March 15, 2022 15:45
Show Gist options
  • Save jsmolina/80312157f95b2b24fe06a38a17f2dea5 to your computer and use it in GitHub Desktop.
Save jsmolina/80312157f95b2b24fe06a38a17f2dea5 to your computer and use it in GitHub Desktop.
React snippet for tracking user enters or leaves a page
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