This commit is contained in:
ct
2025-07-08 03:12:54 +08:00
parent f0ee15b03b
commit 21287e6bc5
4 changed files with 46 additions and 7 deletions

View File

@@ -0,0 +1,27 @@
import { createContext, useContext, useEffect } from 'react';
import ReactGA from 'react-ga4';
const GA4Context = createContext();
export const useGA4 = () => {
const context = useContext(GA4Context);
if (context === undefined) {
throw new Error('useGA4 must be used within a GA4Provider');
}
return context;
};
export const GA4Provider = ({ children }) => {
useEffect(() => {
const GOOGLE_TAG_ID = import.meta.env.VITE_GOOGLE_TAG_ID;
if (GOOGLE_TAG_ID) {
ReactGA.initialize(GOOGLE_TAG_ID);
console.log('Google Analytics 4 initialized with ID:', GOOGLE_TAG_ID);
} else {
console.warn('GA4 is not set. Google Analytics 4 will not be initialized.');
}
}, []);
return <GA4Context.Provider value={ReactGA}>{children}</GA4Context.Provider>;
};