Blog>
Snippets

Track Page Views with React GA in Next.js

Demonstrate how to track page views in a Next.js 14 app using React GA by hooking into the router events.
import ReactGA from 'react-ga';
import { useRouter } from 'next/router';
import { useEffect } from 'react';

const usePageTracking = () => {
  const router = useRouter();

  useEffect(() => {
    ReactGA.initialize('YOUR_TRACKING_ID');
    ReactGA.pageview(window.location.pathname + window.location.search);
  }, []);

  useEffect(() => {
    const handleRouteChange = (url) => {
      ReactGA.pageview(url);
    };

    router.events.on('routeChangeComplete', handleRouteChange);

    // Return function to unsubscribe from the event
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);
};

export default usePageTracking;
Initializes React GA with your tracking ID and sets up listener to track pageviews on route changes.
import usePageTracking from './usePageTracking';

const MyApp = ({ Component, pageProps }) => {
  usePageTracking(); // Call the tracking hook
  
  return <Component {...pageProps} />;
};

export default MyApp;
Implements the custom hook in your Next.js application component to start tracking the pages views.