Skip to content

Instantly share code, notes, and snippets.

@shamilovtim
Created January 11, 2021 17:16
Show Gist options
  • Save shamilovtim/2fc8dda4e04c58323ea87e454e32dc55 to your computer and use it in GitHub Desktop.
Save shamilovtim/2fc8dda4e04c58323ea87e454e32dc55 to your computer and use it in GitHub Desktop.
appstate
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