GTM Data Layer Implementation

Custom Data Layer Implementation for React SPA eCommerce

Custom Data Layer for React SPA

Data layer React SPA case study

๐Ÿ“Œ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.

Talk to with Us, It's Free

We are always willing to help a client in need and answer any questions or provide guidance. Let us know what you are looking for, and we will develop a unique and bespoke solution for you.

โš ๏ธ reCAPTCHA site key is not configured

BUSINESS HOURS

Not Available

ADDRESS

No Address

TOLL FREE

No Phone