El siguiente código muestra una implementación funcional, pero ineficiente, de un BackHandler de Android dentro de React Native para que la aplicación salga después de dos pulsaciones en dos segundos. Esto se implementa utilizando ganchos React dentro del componente funcional principal de la aplicación.
Sin embargo, debido a la dependencia de una variable de estado recentlyPressedHardwareBack , el useEffect se limpiará y luego se ejecutará cada vez que cambie el estado, lo que hará que el detector de eventos BackHandler se desconecte y se vuelva a conectar cada vez que se presione el botón Atrás. ¿Cómo configura este detector de eventos solo una vez sin creación y eliminación constantes, mientras le permite acceder a un estado de componente cambiante?
const [recentlyPressedHardwareBack, setRecentlyPressedHardwareBack] = useState(false); useEffect(() => { const backHandler = BackHandler.addEventListener( 'hardwareBackPress', () => { // Exit app if user pressed the button within last 2 seconds. if (recentlyPressedHardwareBack) { return false; } ToastAndroid.show( 'Press back again to exit the app', ToastAndroid.SHORT, ); setRecentlyPressedHardwareBack(true); // Toast shows for approx 2 seconds, so this is the valid period for exiting the app. setTimeout(() => { setRecentlyPressedHardwareBack(false); }, 2000); // Don't exit yet. return true; }, ); return () => backHandler.remove(); }, [recentlyPressedHardwareBack]);Podrías usar useRef para esto.
const recentlyPressedHardwareBackRef = useRef(false); useEffect(() => { const backHandler = BackHandler.addEventListener( 'hardwareBackPress', () => { // Exit app if user pressed the button within last 2 seconds. if (recentlyPressedHardwareBackRef.current) { return false; } ToastAndroid.show( 'Press back again to exit the app', ToastAndroid.SHORT, ); recentlyPressedHardwareBackRef.current = true; // Toast shows for approx 2 seconds, so this is the valid period for exiting the app. setTimeout(() => { recentlyPressedHardwareBackRef.current = false; }, 2000); // Don't exit yet. return true; }, ); return () => backHandler.remove(); }, [])