Fix: Google Analytics and GTM initialize on every render causing duplicate events
- Dominant language
- TypeScript
- Stars
- 716
- Forks
- 1.2k
- Avg merge
- 1d 12h
- Merged PRs (30d)
- 35
Description
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 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
Contributor guide
Research direction
Start in Head.tsx at HeadComponent and inspect how analytics initialization currently runs during rendering. Move the initialization and pageview behavior to mount-time handling, then verify that rerendering the component does not produce duplicate analytics initialization or pageview events.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- nextjs, react, typescript
- Domain
- frontend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 68/100