How to dynamically control tracking in react-ga4?

86 views Asked by At

I have a React Project that host in Firebase.

I use react-ga4 package and work fine. (Not react-ga)

But I want only work react-ga4 if user enable this. And later the user can enable or disable this.

I want solve this with the best practice!

Now i have state name "consent" that save localstorage

consent state represent user enable and disable the tracking.

consentModel is also a state and save and read also to localstorage that represent user have choosed once

Here is my simple idea. Is it work properly?

  const {    
    consent,
    setConsent,
    consentModel,
    setConsentModel,
  } = useStyleContext();
import ReactGA from "react-ga4";

//ReactGA.initialize("G-xxxxxxxx");

const hideConsentModel = () => {
    setConsentModel(false);
    localStorage.setItem("consentmodel", "false");
  };

  const enableCookie = () => {
    setConsent(true);
  };

  const disableCookie = () => {
    setConsent(false);
  };

  useEffect(() => {
    const consentFromLocalStorage = localStorage.getItem("consent");
    if (consentFromLocalStorage) {
      setConsentModel(false);
    }
  }, []);

  useEffect(() => {
    localStorage.setItem("consent", consent ? "true" : "false");
  }, [consent]);

  useEffect(() => {
    if (consent) {
      // If the user has agreed, we initialize the tracking.
      ReactGA.initialize("G-xxxxxxxxxx");
    } else {
      console.log("No tracking");
    }
  }, [consent]);

return(
  {consentModel && (
        <UserConsentModelem
          enableCookie={enableCookie}
          disableCookie={disableCookie}
          onClose={hideConsentModel}
        />
      )}
)

So the key part this work properly?

 useEffect(() => {
    if (consent) {
      // If the user has agreed, we initialize the tracking.
      ReactGA.initialize("G-xxxxxxxxxx");
    } else {
      console.log("No tracking");
    }
  }, [consent]);

Thank you

0

There are 0 answers