import { useEffect } from 'react' ; import { useRouter } from 'next/router' ; import posthog , { PostHog } from 'posthog-js' ; let POSTHOG_INSTANCE ; export const usePostHog = ( apiKey , config ? , name ? ) : void => { const router = useRouter ( ) ; if ( config . loaded ) { const oldLoaded = config . loaded ; config . loaded = ( posthog ) => { setPostHogInstance ( posthog ) ; oldLoaded ( POSTHOG_INSTANCE ) ; } ; } else { config . loaded = setPostHogInstance ; } useEffect ( ( ) : ( ( ) => void ) => { if ( typeof window === undefined ) return ; posthog . init ( apiKey , config , name ) ; const handleRouteChange = ( ) => posthog . capture ( '$pageview' ) ; router . events . on ( 'routeChangeComplete' , handleRouteChange ) ; return ( ) => { router . events . off ( 'routeChangeComplete' , handleRouteChange ) ; } ; } , [ router . events ] ) ; } ; const setPostHogInstance = ( posthog ) => { POSTHOG_INSTANCE = posthog ; } ; export const getPostHogInstance = ( ) : PostHog => { return POSTHOG_INSTANCE ; } ;