-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseGoogleAnalytics.ts
More file actions
51 lines (47 loc) · 1.14 KB
/
useGoogleAnalytics.ts
File metadata and controls
51 lines (47 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { useEffect } from 'react'
import ReactGA from 'react-ga4'
/**
* Initialize Google Analytics with tracking ID
* Must be called once during app initialization
*/
export const initializeGoogleAnalytics = (trackingId: string): void => {
if (!trackingId) {
console.warn('Google Analytics: Tracking ID not provided')
return
}
ReactGA.initialize(trackingId)
}
/**
* Hook to track page views when route changes
* Should be used in the root router component
*/
export const useGoogleAnalyticsPageView = (pathname: string): void => {
useEffect(() => {
// Send page view to Google Analytics
ReactGA.send({
hitType: 'pageview',
page: pathname,
title: document.title
})
}, [pathname])
}
/**
* Track custom events in Google Analytics
* @param category - Event category (e.g., 'engagement')
* @param action - Event action (e.g., 'click')
* @param label - Event label (optional)
* @param value - Event value (optional)
*/
export const trackGAEvent = (
category: string,
action: string,
label?: string,
value?: number
): void => {
ReactGA.event({
category,
action,
label,
value
})
}