Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

backHandler.ts

19 lines885 Bytes

1import { useIsFocused } from "@react-navigation/native";
2import { useEffect, useEffectEvent } from "react";
3import { BackHandler } from "react-native";
4​
5/**
6 * Android hardware back while `active` and the owning screen is focused.
7 * Keyed on those alone, not `onBack`: BackHandler calls the newest listener
8 * first, so re-registering per render lets a covered screen consume Back.
9 */
10export function useHardwareBack(active: boolean, onBack: () => boolean) {
11 const focused = useIsFocused();
12 const handleBack = useEffectEvent(onBack);
13 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to BackHandler for the focused screen's lifetime
14 useEffect(() => {
15 if (!active || !focused) return;
16 const subscription = BackHandler.addEventListener("hardwareBackPress", () => handleBack());
17 return () => subscription.remove();
18 }, [active, focused]);