Skip to content

Instantly share code, notes, and snippets.

@benoitdion
Created June 3, 2019 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benoitdion/cbb2a6861a03e0a6a40c4c33f6cc2a22 to your computer and use it in GitHub Desktop.
Save benoitdion/cbb2a6861a03e0a6a40c4c33f6cc2a22 to your computer and use it in GitHub Desktop.
useEffect hooks are not flushed when app is backgrounded
import React, { Component, useState, useEffect, useLayoutEffect } from "react";
import { Text, AppState } from "react-native";
export const useAppState = () => {
const [appState, setAppState] = useState(AppState.currentState);
useEffect(() => {
const onChange = newState => {
setAppState(newState);
};
AppState.addEventListener('change', onChange);
return () => {
AppState.removeEventListener('change', onChange);
};
}, []);
return appState;
};
const AppStateView = () => {
const appState = useAppState();
useEffect(() => {
console.log(">>> [useEffect] new app state:", appState);
}, [appState]);
useLayoutEffect(() => {
console.log(">>> [useLayoutEffect] new app state:", appState);
}, [appState]);
return <Text>{appState}</Text>;
};
export default class App extends Component {
render() {
return <AppStateView />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment