I use the AppState API listener to run a function when the app comes from background to active state. I remove it on the useEffect cleanup, but it is still being called on the other screens like it was never cleaned.
const MyRoute = ({ navigation, route }) => {
const appStateRef = useRef(AppState.currentState);
useEffect(() => {
getUserData();
function updateRouteData(nextAppState) {
if (appStateRef.current.match(/inactive|background/) && nextAppState === 'active') {
getRoutes(); // <--
}
appStateRef.current = nextAppState;
}
AppState.addEventListener('change', updateRouteData);
return () => {
AppState.removeEventListener('change', updateRouteData);
};
}, []);
// ...
}
The AppState event listener persists on the other screens.
react-native: "0.64.4"
2
Answers
I found a solution.
Instead of calling the appstate logic inside a useEffect, I call it with the useFocusEffect from the react navigation. When leaving the screen you can trigger a cleanup function to remove the listener.
I created a custom hook to use it on my app.
Get the event listener in a variable and then remove it.