skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    const useAppStateListener = (callback) => {
      const appStateRef = useRef(AppState.currentState);
    
      useFocusEffect(
        useCallback(() => {
          async function updateRouteData(nextAppState) {
            if (appStateRef.current.match(/inactive|background/) && nextAppState === 'active') {
              await callback();
            }
    
            appStateRef.current = nextAppState;
          }
    
          AppState.addEventListener('change', updateRouteData);
    
          return () => {
            AppState.removeEventListener('change', updateRouteData);
          };
        }, [callback]),
      );
    
      return appStateRef;
    };
    

  2. Get the event listener in a variable and then remove it.

    const appStateListener = AppState.addEventListener()
    
    appStateListener?.remove();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search