Created
January 11, 2021 17:16
-
-
Save shamilovtim/2fc8dda4e04c58323ea87e454e32dc55 to your computer and use it in GitHub Desktop.
appstate
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 } from 'react'; | |
import { AppState } from 'react-native'; | |
export default function useAppState(settings) { | |
const { onChange, onForeground, onBackground } = settings || {}; | |
const [appState, setAppState] = useState(AppState.currentState); | |
useEffect(() => { | |
function handleAppStateChange(nextAppState) { | |
if (nextAppState === 'active' && appState !== 'active') { | |
isValidFunction(onForeground) && onForeground(); | |
} else if (appState === 'active' && nextAppState.match(/inactive|background/)) { | |
isValidFunction(onBackground) && onBackground(); | |
} | |
setAppState(nextAppState); | |
isValidFunction(onChange) && onChange(nextAppState); | |
} | |
AppState.addEventListener('change', handleAppStateChange); | |
return () => AppState.removeEventListener('change', handleAppStateChange); | |
}, [onChange, onForeground, onBackground, appState]); | |
// settings validation | |
function isValidFunction(func) { | |
return func && typeof func === 'function'; | |
} | |
return { appState }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment