Skip to content

Commit

Permalink
feat: add google analytics via react-ga4
Browse files Browse the repository at this point in the history
  • Loading branch information
HJunyuan committed Aug 5, 2024
1 parent 5489533 commit 1f90da9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import React from "react";
import { Router } from "./router";
import { useGoogleAnalytics } from "./utils/google-analytics";

export const App: React.FunctionComponent = () => (
<div className="flex flex-col min-h-screen">
<Router />
</div>
);
export const App: React.FunctionComponent = () => {
useGoogleAnalytics();
return (
<div className="flex flex-col min-h-screen">
<Router />
</div>
);
};
20 changes: 20 additions & 0 deletions src/utils/google-analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { useEffect } from "react";
import ReactGA from "react-ga4";

/**
* Initialise Google Analytics 4 only once (if GTAG_ID is provided)
*
* The ReactGA.send("pageview") is explicitly called afterwards because
* the pageview event is not automatically triggered on first initialisation
* but will be automatically triggered by the GA script on subsequent page views.
*/
export const useGoogleAnalytics = (): void => {
useEffect(() => {
try {
ReactGA.initialize("G-GXV2BSGK4K");
ReactGA.send("pageview");
} catch (e) {
console.error(e);
}
}, []);
};

0 comments on commit 1f90da9

Please sign in to comment.