Files
memefast/resources/js/plugins/GA4Context.jsx
2025-07-08 03:12:54 +08:00

28 lines
848 B
JavaScript

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>;
};