I am using React GA to track analytics. Two useEffect hooks, first one to check condition (do not initialize if in dev, on localhost). The second useEffect to track pageview. I am getting a warning
ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually.
How do I ensure that ReactGA.initialize is called first?
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";
import { GA_TRACKING_NUMBER } from './config/google';
import APP from './config/constants';
const GoogleAnalytics = () => {
const location = useLocation();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if (!window.location.href.includes("localhost")) {
// initializing Google Analytics:
ReactGA.initialize(GA_TRACKING_NUMBER, { debug: APP.isDevMode });
}
setInitialized(true);
}, []);
useEffect(() => {
if (initialized) {
ReactGA.pageview(location.pathname + location.search);
}
}, [initialized, location]);
return null;
};
export default GoogleAnalytics;