Joshua Augustinus
Joshua Augustinus

Reputation: 1670

Need to run code when React Native app closing

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.

Upvotes: 3

Views: 5396

Answers (2)

root
root

Reputation: 173

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');
  }    
}

Upvotes: 1

Chanuka Sandeepa
Chanuka Sandeepa

Reputation: 720

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');
  }    
}

Upvotes: 7

Related Questions