// src/hooks/usePageTracking.js import { useEffect, useRef } from 'react'; import { useLocation } from 'react-router-dom'; import posthog from 'posthog-js'; /** * Custom hook for automatic page view tracking with PostHog * * @param {Object} options - Configuration options * @param {boolean} options.enabled - Whether tracking is enabled * @param {Function} options.getProperties - Function to get custom properties for each page view */ export const usePageTracking = ({ enabled = true, getProperties } = {}) => { const location = useLocation(); const previousPathRef = useRef(''); useEffect(() => { if (!enabled) return; // Get the current path const currentPath = location.pathname + location.search; // Skip if it's the same page (prevents duplicate tracking) if (previousPathRef.current === currentPath) { return; } // Update the previous path previousPathRef.current = currentPath; // Get custom properties if function provided const customProperties = getProperties ? getProperties(location) : {}; // Track page view with PostHog if (posthog && posthog.__loaded) { posthog.capture('$pageview', { $current_url: window.location.href, path: location.pathname, search: location.search, hash: location.hash, ...customProperties, }); // Log in development if (process.env.NODE_ENV === 'development') { console.log('📊 PostHog $pageview:', { path: location.pathname, ...customProperties, }); } } }, [location, enabled, getProperties]); }; export default usePageTracking;