From 059dc01ab896aef96aa75e228591e8436c78b68c Mon Sep 17 00:00:00 2001 From: Whitewater Date: Tue, 15 Apr 2025 12:50:45 +0900 Subject: [PATCH] feat: add useBackHandler hook for handling hardware back press on Android (#3493) --- apps/mobile/src/App.tsx | 2 ++ apps/mobile/src/hooks/useBackHandler.ts | 28 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 apps/mobile/src/hooks/useBackHandler.ts diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index f228e9697..0cb63e64e 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -4,6 +4,7 @@ import Animated, { interpolate, useAnimatedStyle } from "react-native-reanimated import { RootSiblingParent } from "react-native-root-siblings" import { useSheet } from "react-native-sheet-transitions" +import { useBackHandler } from "./hooks/useBackHandler" import { useIntentHandler } from "./hooks/useIntentHandler" import { DebugButton, EnvProfileIndicator } from "./modules/debug" import { usePrefetchActions } from "./store/action/hooks" @@ -15,6 +16,7 @@ export function App({ children }: { children: React.ReactNode }) { useIntentHandler() useOnboarding() useUnreadCountBadge() + useBackHandler() // prefetch actions to detect if the user has any actions contains notifications usePrefetchActions() diff --git a/apps/mobile/src/hooks/useBackHandler.ts b/apps/mobile/src/hooks/useBackHandler.ts new file mode 100644 index 000000000..4e286af4a --- /dev/null +++ b/apps/mobile/src/hooks/useBackHandler.ts @@ -0,0 +1,28 @@ +import { useEffect } from "react" +import { BackHandler } from "react-native" + +import { useCanDismiss, useNavigation } from "../lib/navigation/hooks" +import { isAndroid } from "../lib/platform" + +export const useBackHandler = () => { + const navigation = useNavigation() + const canDismiss = useCanDismiss() + + useEffect(() => { + if (!isAndroid) return + + // eslint-disable-next-line @eslint-react/web-api/no-leaked-event-listener -- listener.remove() handles cleanup + const listener = BackHandler.addEventListener("hardwareBackPress", () => { + if (canDismiss) { + navigation.dismiss() + } else { + navigation.back() + } + return true + }) + + return () => { + listener.remove() + } + }, [canDismiss, navigation]) +}