Created
June 3, 2019 14:02
-
-
Save benoitdion/cbb2a6861a03e0a6a40c4c33f6cc2a22 to your computer and use it in GitHub Desktop.
useEffect hooks are not flushed when app is backgrounded
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 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