Skip to content

Instantly share code, notes, and snippets.

@jtomchak
Created March 4, 2024 16:54
Show Gist options
  • Save jtomchak/97fd98a61fc207a000d26d6dc38eb8b0 to your computer and use it in GitHub Desktop.
Save jtomchak/97fd98a61fc207a000d26d6dc38eb8b0 to your computer and use it in GitHub Desktop.
import React, { useEffect, useRef, useState } from "react";
import { AppState } from "react-native";
/**
* Returns 'inactive | active | background'
*/
export const useAppState = () => {
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = useState(appState.current);
useEffect(() => {
const subscription = AppState.addEventListener("change", (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
});
return () => {
subscription.remove();
};
});
return appStateVisible;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment