website icon indicating copy to clipboard operation
website copied to clipboard

Fix: Google Analytics and GTM initialize on every render causing duplicate events

Open sammy200-ui opened this issue 1 month ago • 5 comments

I was exploring the codebase and noticed a potential issue in Head.tsx regarding how we handle analytics initialization.

Currently, the ReactGA.initialize TagManager.initialize, and ReactGA.pageview calls are placed directly inside the component body of HeadComponent

  if (typeof window !== 'undefined' && window.location.hostname.includes('asyncapi.com')) {
    TagManager.initialize({ gtmId: 'GTM-T58BTVQ' });
    ReactGA.initialize('UA-109278936-1');
    ReactGA.pageview(window.location.pathname + window.location.search);
  }

Because this logic isn't wrapped in a useEffect or componentDidMount, it executes every time the HeadComponent re-renders.

We should wrap this logic in a useEffect hook with an empty dependency array. This ensures it only runs once when the component mounts, which is the intended behavior for a page view.

@princerajpoot20 @thulieblack do you guys think this needs to be done , would like to know your thoughts on this!! , i could raise a pr for the same

sammy200-ui avatar Nov 26 '25 18:11 sammy200-ui

Hi, @sammy200-ui I would like to work on it.

AdityaTile04 avatar Nov 26 '25 18:11 AdityaTile04

Hey! @AdityaTile04 Thanks for your interest 😊 I’m already actively working on this issue and should have an update soon depending on the mentors approval

sammy200-ui avatar Nov 26 '25 18:11 sammy200-ui

Hi! @AdityaTile04 @sammy200-ui I'd like to work on this issue i am a new contributor. Here's my proposed solution:

Problem: In Head.tsx, analytics initialization (TagManager.initialize, ReactGA.initialize, ReactGA.pageview) runs inside the component body. This causes the analytics setup to execute on every re-render instead of only once.

Proposed Solution: Move the analytics initialization into a useEffect with an empty dependency array. This ensures it runs only on component mount, preventing duplicate initialization and repeated pageview events.

Key Steps:

Wrap the existing analytics block in useEffect(() => { ... }, []).

Ensure the logic still checks for window !== undefined and valid hostname.

Verify only one pageview is fired on first load.

Timeline: PR ready within one day.

ShreyasN707 avatar Nov 29 '25 04:11 ShreyasN707

Hello @ShreyasN707 i have already implement the issue as mentioned previously .Just waiting on maintainer approval. Thanks for your interest

sammy200-ui avatar Nov 29 '25 07:11 sammy200-ui

hey @princerajpoot20 just a follow up on this issue , what do you say , will this affect in the long run ?

sammy200-ui avatar Dec 04 '25 18:12 sammy200-ui