Fix: Google Analytics and GTM initialize on every render causing duplicate events
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
Hi, @sammy200-ui I would like to work on it.
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
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.
Hello @ShreyasN707 i have already implement the issue as mentioned previously .Just waiting on maintainer approval. Thanks for your interest
hey @princerajpoot20 just a follow up on this issue , what do you say , will this affect in the long run ?