1

I use react-gtm-module (version 2.0.11) to create Google Tag Manager for my ReactJs app.

My problem is that each time a component renders, the function TagManager.initialize runs again. This creates duplicate GTM scripts (as attached).

I have to get gtm-ID from other data which changes many times. Each time this data changes, my component renders.

Is there a way to avoid the function TagManager.initialize run again if my GTM is already initialized?

My code:

useEffect(() => {
   if (data.gtm_id){
     TagManager.initialize({
      gtmId: data.gtm_id,
     });
   }
}, [data.gtm_id])

Thank you so much.

enter image description here

vanminhquangtri
  • 145
  • 1
  • 9

1 Answers1

0

If you add a check for any object added by TagManager, like dataLayer or google_tag_data in window, you can prevent unnecessary reinitializations.

useEffect(() => {
   if (data.gtm_id && !window.dataLayer){
     TagManager.initialize({
      gtmId: data.gtm_id,
     });
   }
}, [data.gtm_id])