Created
February 22, 2020 17:09
-
-
Save wouterds/51fe9f226d05a02976d82db6a2e10d7c to your computer and use it in GitHub Desktop.
React Native useAppState hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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