forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-google-analytics.tsx
More file actions
29 lines (25 loc) · 1.11 KB
/
Copy pathuse-google-analytics.tsx
File metadata and controls
29 lines (25 loc) · 1.11 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
"use client";
import { usePathname } from "next/navigation";
import { useEffect } from "react";
import ReactGA from "react-ga4";
import { normalizePathnameForAnalytics } from "@/lib/analytics-utils";
import { getRuntimeConfig } from "@/lib/runtime-config.client";
export function useGoogleAnalytics() {
// Tracking ID is read at render time from the runtime config injected
// by the root layout. Empty string disables GA — but the gating MUST
// live INSIDE the effect bodies, not as an early return, otherwise
// React's rules-of-hooks are violated (hooks below the conditional
// return would be skipped on renders where GA is disabled, which
// changes hook order between renders and crashes React).
const GA_ID = getRuntimeConfig().googleAnalyticsTrackingId;
const pathname = usePathname();
useEffect(() => {
if (!GA_ID) return;
ReactGA.initialize([{ trackingId: GA_ID }]);
}, [GA_ID]);
useEffect(() => {
if (!GA_ID) return;
const normalizedPathname = normalizePathnameForAnalytics(pathname);
ReactGA.send({ hitType: "pageview", page: normalizedPathname });
}, [pathname, GA_ID]);
}