Get the root navigator state and find the active route name
To get notified of state changes, we can use the onStateChange prop on NavigationContainer. To get the root navigator state, we can use the getRootState method on the container's ref. Please note that onStateChange is not called on initial render so you have to set your initial screen separately.
import{NavigationContainer,useNavigationContainerRef,}from'@react-navigation/native';exportdefault()=>{constnavigationRef=useNavigationContainerRef();constrouteNameRef=useRef();return(<NavigationContainerref={navigationRef}onReady={()=>{routeNameRef.current=navigationRef.getCurrentRoute().name;}}onStateChange={async()=>{constpreviousRouteName=routeNameRef.current;constcurrentRouteName=navigationRef.getCurrentRoute().name;consttrackScreenView=()=>{// Your implementation of analytics goes here!};if(previousRouteName!==currentRouteName){// Save the current route name for later comparisonrouteNameRef.current=currentRouteName;// Replace the line below to add the tracker from a mobile analytics SDKawaittrackScreenView(currentRouteName);}}}>{/* ... */}</NavigationContainer>);};