Skip to content

Instantly share code, notes, and snippets.

@wouterds
Created February 22, 2020 17:09
Show Gist options
  • Save wouterds/51fe9f226d05a02976d82db6a2e10d7c to your computer and use it in GitHub Desktop.
Save wouterds/51fe9f226d05a02976d82db6a2e10d7c to your computer and use it in GitHub Desktop.
React Native useAppState hook
import { useState, useEffect, useCallback } from 'react';
import { AppState, AppStateStatus } from 'react-native';
const useAppState = () => {
const [appState, setAppState] = useState(AppState.currentState);
const handleAppStateChange = useCallback(
(nextAppState: AppStateStatus) => {
setAppState(nextAppState);
},
[setAppState],
);
useEffect(() => {
AppState.addEventListener('change', handleAppStateChange);
return () => AppState.removeEventListener('change', handleAppStateChange);
}, [appState, handleAppStateChange]);
return appState;
};
export default useAppState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment