fix: report every page view from the route effect

The route effect ran before App initialized react-ga4, so its first
page view was dropped and the landing page was only counted by gtag's
automatic page_view.

- initialize react-ga4 once at module load
- pass send_page_view: false and send one page view per route change
- include the query string in the page path
- only track production builds
This commit is contained in:
2026-09-14 13:50:20 +09:00
parent df2c671844
commit 4dcafe0673
+13 -5
View File
@@ -10,11 +10,22 @@ import News from './features/news/News';
import PageTitle from './features/page-title/PageTitle';
import Search from './features/search/Search';
const GOOGLE_ANALYTICS_TRACKING_ID = 'G-T4L3SDCN6P';
const isAnalyticsEnabled = import.meta.env.PROD;
if (isAnalyticsEnabled) {
// Page views are sent from the location effect in AppMain, the first one included;
// gtag's own page_view on config would count the landing page twice.
ReactGA.initialize(GOOGLE_ANALYTICS_TRACKING_ID, { gtagOptions: { send_page_view: false } });
}
const AppMain: React.FC = () => {
const location = useLocation();
React.useEffect(() => {
ReactGA.send({ hitType: 'pageview', page: location.pathname });
}, [location]);
if (isAnalyticsEnabled) {
ReactGA.send({ hitType: 'pageview', page: location.pathname + location.search });
}
}, [location.pathname, location.search]);
return (
<div className={styles.container}>
@@ -51,9 +62,6 @@ const AppMain: React.FC = () => {
};
const App: React.FC = () => {
React.useEffect(() => {
ReactGA.initialize('G-T4L3SDCN6P');
}, []);
return (
<BrowserRouter>
<AppMain />