Custom Data Layer Implementation for React SPA eCommerce
Custom Data Layer for React SPA

๐Introduction
A React single-page application eCommerce store needed a robust data layer implementation to track user interactions and eCommerce events in an environment where traditional GTM page-view triggers do not function as expected.
โThe Problem
Standard GTM page view triggers fire only on full page loads. In a React SPA, page navigation happens without full reloads, causing GTM to miss all subsequent page views and events after the initial page load. The client was only seeing entry page data.
๐Identifying the Causes
React Router was handling all navigation client-side. GTM's window.onload trigger never re-fired. Push State changes (history.pushState) were not being used as triggers. The dataLayer was not being pushed on route changes, and ecommerce events were being triggered before the dataLayer was initialized.
โ ๏ธConsequences for the Business
Analytics showed every user as a single-page session regardless of how many products they browsed. Funnel analysis was impossible. Over 90% of ecommerce data was missing because add_to_cart and purchase events fired before GTM was ready to capture them.
โ Solution
Implemented a custom React hook (useGTMDataLayer) that pushed dataLayer events on every React Router location change. Created an event queue that buffered ecommerce events until GTM was initialized. Built wrapper components for product listing, product detail, cart, and checkout that automatically pushed the appropriate dataLayer events as users interacted.
๐Results
Page view tracking increased from capturing 1 page per session average to 4.7 pages (the actual browsing behavior). Ecommerce funnel became fully visible for the first time. Funnel analysis immediately identified that 73% of mobile users abandoned on the product detail page, leading to mobile UX improvements that increased mobile conversion by 22%.
๐Conclusion
React SPAs require a fundamentally different GTM/analytics strategy than traditional multi-page applications. A dedicated dataLayer architecture designed for React's lifecycle is essential.
๐กKey Takeaways
Never use GTM's All Pages trigger in a React SPA โ use History Change trigger or push virtual pageviews manually. Initialize an event queue before GTM loads to prevent missed events. Wrap ecommerce components with dataLayer push logic for automatic, consistent tracking.