UNPKG

unified-analytics

Version:

Unified analytics library for web applications

66 lines (65 loc) 2.66 kB
import { useEffect, useRef } from 'react'; import analytics from '..'; /** * Custom hook to track screen duration * @param screenName - The name of the screen/event to track * @param additionalAttributes - Additional attributes to include with the analytics event */ export const useScreenDuration = (screenName, additionalAttributes = {}) => { const startTime = useRef(0); useEffect(() => { startTime.current = Date.now(); return () => { const endTime = Date.now(); const duration = (endTime - startTime.current) / 1000; // Track the screen duration event analytics.sendEvent(screenName, { duration, openTimestamp: startTime.current, closeTimestamp: endTime, ...additionalAttributes, }); }; }, [screenName, additionalAttributes]); return null; }; /** * Custom hook to track scroll depth * @param eventName - The name of the event to track when scrolling * @param throttleMs - Throttle time in milliseconds (default: 500ms) * @param additionalAttributes - Additional attributes to include with the analytics event */ export const useScrollDepthTracking = (eventName, throttleMs = 500, additionalAttributes = {}) => { const lastScrollTime = useRef(0); // Function to track scroll with throttling const trackScroll = () => { const now = Date.now(); // Throttle based on provided value if (now - lastScrollTime.current >= throttleMs) { lastScrollTime.current = now; // Get current scroll position const scrollY = window.scrollY; // Calculate scroll depth percentage (0-100) const scrollHeight = document.documentElement.scrollHeight; const clientHeight = document.documentElement.clientHeight; const scrollDepth = scrollHeight <= clientHeight ? 0 : Math.min(100, Math.round((scrollY / (scrollHeight - clientHeight)) * 100)); // Track the scroll event with only the scroll depth analytics.sendEvent(eventName, { scrollDepth, timestamp: now, ...additionalAttributes, }); } }; useEffect(() => { // Add scroll event listener with throttling window.addEventListener("scroll", trackScroll, { passive: true }); return () => { // Remove the scroll event listener window.removeEventListener("scroll", trackScroll); }; }, [eventName, throttleMs, additionalAttributes]); return null; };