import { NavigationContainerRefWithCurrent } from '@react-navigation/core' import { useCallback, useRef } from 'react' import { navigationRef } from '@/utils' type Callback = (currentRouteName: string) => Promise | undefined const defaultCallback: Callback = async (currentRouteName) => { // TODO: Add analytics logs here // console.log(`Current route: ${currentRouteName}`) } type ScreenTrackerReturn = { navigationRef: NavigationContainerRefWithCurrent onReady: () => void onStateChange: () => Promise } // TODO: make this work on expo router export const useScreenTracker = (callback = defaultCallback): ScreenTrackerReturn => { const routeNameRef = useRef() const onReady = useCallback(() => { routeNameRef.current = navigationRef?.getCurrentRoute()?.name }, []) const onStateChange = useCallback(async () => { const previousRouteName = routeNameRef.current const currentRouteName = navigationRef?.getCurrentRoute()?.name if (previousRouteName !== currentRouteName) { if (currentRouteName) { await callback(currentRouteName) } } routeNameRef.current = currentRouteName }, [callback]) return { navigationRef, onReady, onStateChange } }