Reputation: 1670
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
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
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