Need to run code when React Native app closing

Viewed 1812

I tried using a useEffect hook in the App component like this:

  useEffect(() => {
    console.log('App mounted');

    return () => {
      console.log('App unmounted');
    };
  }, []);

However the console doesn't show the App unmounted message. Tested on an Android device with a blank app. The way I closed the app was by pressing ||| on the tablet and then Close All.

2 Answers

I recommend you to use AppState.

useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange);

    return () => {
      AppState.removeEventListener('change', handleAppStateChange);
    };
 }, []);

const handleAppStateChange = (nextAppState) => {
  if (nextAppState === 'inactive') {
    console.log('the app is closed');
  }    
}

removeEventListener() is now deprecated you should use remove() instead

You can check this doc in detail.

https://reactnative.dev/docs/0.67/appstate#removeeventlistener

useEffect(() => {
    const appStateId = AppState.addEventListener('change', handleAppStateChange);

    return () => {
      appStateId.remove(console.log('the app is closed'));
    };
 }, []);

const handleAppStateChange = (nextAppState) => {
  if (nextAppState === 'inactive') {
    console.log('the app is closed');
  }    
}
Related