import { useCallback, useRef } from "react"; import { BackHandler, type NativeEventSubscription } from "react-native"; import type { BottomSheetModal } from "@gorhom/bottom-sheet"; /** * Hook that dismisses the bottom sheet modal on the hardware back button press if it is visible * @param bottomSheetRef ref to the bottom sheet component */ export function useBottomSheetBackHandler( bottomSheetRef: React.RefObject, ): { handleSheetPositionChange: (index: number) => void; } { const backHandlerSubscriptionRef = useRef( null, ); const handleSheetPositionChange = useCallback( (index: number) => { const isBottomSheetVisible = index >= 0; if (isBottomSheetVisible && !backHandlerSubscriptionRef.current) { // Setup the back handler if the bottom sheet is right in front of the user backHandlerSubscriptionRef.current = BackHandler.addEventListener( "hardwareBackPress", () => { bottomSheetRef.current?.dismiss(); return true; }, ); } else if (!isBottomSheetVisible) { backHandlerSubscriptionRef.current?.remove(); backHandlerSubscriptionRef.current = null; } }, [bottomSheetRef], ); return { handleSheetPositionChange }; }