Skip to content
Source
Sign inSign up

backHandler.ts

23 lines1.0 KB

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