Skip to content

Instantly share code, notes, and snippets.

@giacomocerquone
Last active October 27, 2019 19:58
Show Gist options
  • Save giacomocerquone/f3f5feb2ff9f8570855ce30792d49d9f to your computer and use it in GitHub Desktop.
Save giacomocerquone/f3f5feb2ff9f8570855ce30792d49d9f to your computer and use it in GitHub Desktop.
Class to Hooks example
class AppStateChecker extends React.Component {
constructor() {
this.state = {
appState: AppState.currentState,
};
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_backgroundState(state) {
return state.match(/inactive|background/);
}
_handleAppStateChange = (nextAppState) => {
if (this._backgroundState(nextAppState)) {
console.log("App is going background");
} else if (this._backgroundState(this.state.appState) && (nextAppState === 'active')) {
console.log("App is coming to foreground");
}
this.setState({appState: nextAppState});
}
render() {
return null
}
}
function AppStateChecker() {
const cachedAppState = useRef(AppState.currentState);
const _handleAppStateChange = useCallback(nextAppState => {
console.log(cachedAppState.current, nextAppState);
if (_backgroundState(nextAppState)) {
console.log('App is going background');
} else if (
_backgroundState(cachedAppState.current) &&
nextAppState === 'active'
) {
console.log('App is coming to foreground');
}
cachedAppState.current = nextAppState;
}, []);
useEffect(() => {
NetInfo.isConnected.addEventListener('connectionChange', setConnected);
AppState.addEventListener('change', _handleAppStateChange);
return () => {
NetInfo.isConnected.removeEventListener('connectionChange', setConnected);
AppState.removeEventListener('change', _handleAppStateChange);
};
}, []);
return null;
}
// INFO: here everything works like the class component
function AppStateChecker() {
const [cachedAppState, setCachedAppState] = useState(AppState.currentState);
const _handleAppStateChange = useCallback(nextAppState => {
console.log(cachedAppState, nextAppState);
if (_backgroundState(nextAppState)) {
console.log('App is going background');
} else if (
_backgroundState(cachedAppState) &&
nextAppState === 'active'
) {
console.log('App is coming to foreground');
}
setCachedAppState(nextAppState);
}, []);
useEffect(() => {
NetInfo.isConnected.addEventListener('connectionChange', setConnected);
AppState.addEventListener('change', _handleAppStateChange);
return () => {
NetInfo.isConnected.removeEventListener('connectionChange', setConnected);
AppState.removeEventListener('change', _handleAppStateChange);
};
}, []);
return null;
}
// INFO: basically when the RN app comes to foreground (after being in multitasking) it's like cachedAppState have never received the new value through setCachedAppState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment