Blog>
Snippets

Adding a Custom Analytics Hook

Create a custom React hook in Next.js 14 for useAnalytics to track events and page views, making analytics integration easier across components.
import { useRouter } from 'next/router';
import { useEffect } from 'react';

// Custom hook for analytics
export const useAnalytics = () => {
  const router = useRouter();

  // This function can be used to track custom events
  const trackEvent = (event) => {
    // Integrate with your analytics service
    console.log('Tracking event:', event);
  };

  // This function can be used to track page views
  const trackPageView = (url) => {
    // Integrate with your analytics service
    console.log('Page view tracked:', url);
  };

  // Effect to track page views on route change
  useEffect(() => {
    const handleRouteChange = (url) => {
      trackPageView(url);
    };

    // Subscribe to route changes
    router.events.on('routeChangeComplete', handleRouteChange);

    // Unsubscribe from events on cleanup
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return { trackEvent, trackPageView };
};
This code defines a custom React hook `useAnalytics` that provides two functions: `trackEvent` for tracking custom analytics events and `trackPageView` for tracking page views. The hook uses the `useEffect` to subscribe to Next.js router events and automatically track page views when the route changes. It includes cleanup logic to unsubscribe from the router events and avoid memory leaks. Integration with a specific analytics service should replace the `console.log` statements.