feat: add useBackHandler hook for handling hardware back press on Android (#3493)

This commit is contained in:
Whitewater
2025-04-15 11:50:45 +08:00
committed by GitHub
parent b472db3b8e
commit 059dc01ab8
2 changed files with 30 additions and 0 deletions
+2
View File
@@ -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()
+28
View File
@@ -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])
}