import { useEffect, useRef } from 'react';
import { getAnalytics } from '../core/AnalyticsManager';
/**
* Hook that auto-tracks screen views from Expo Router.
*
* Uses `usePathname` and `useSegments` from expo-router internally.
* Drop it anywhere in your root layout:
*
* ```tsx
* // app/_layout.tsx
* import { useExpoRouterTracking } from 'react-native-analytics-bridge';
*
* export default function RootLayout() {
* useExpoRouterTracking();
* return ;
* }
* ```
*
* Note: expo-router is a peer dependency — install it separately.
*/
export function useExpoRouterTracking(options?: {
/** Extra properties to attach to every screen event */
extraProperties?: Record;
/**
* Custom function to derive a human-readable screen name from the pathname.
* Defaults to using the pathname directly.
*/
getScreenName?: (pathname: string, segments: string[]) => string;
}) {
// Dynamic imports so the package doesn't hard-require expo-router
let usePathname: () => string;
let useSegments: () => string[];
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const expoRouter = require('expo-router');
usePathname = expoRouter.usePathname;
useSegments = expoRouter.useSegments;
} catch {
console.warn(
'[AnalyticsBridge] expo-router not found. Install it to use useExpoRouterTracking.'
);
return;
}
const pathname = usePathname();
const segments = useSegments();
const previousPathRef = useRef(undefined);
useEffect(() => {
const screenName = options?.getScreenName
? options.getScreenName(pathname, segments)
: pathname;
if (screenName !== previousPathRef.current) {
try {
getAnalytics().screen(screenName, {
pathname,
segments: segments.join('/'),
previous_screen: previousPathRef.current,
...options?.extraProperties,
});
} catch {
// Analytics not yet initialized — skip silently
}
previousPathRef.current = screenName;
}
}, [pathname]);
}