Michael L. Michael L. - 4 months ago 36
Javascript Question

React Native: Is there a callback function for when your app is closed?

I have a setInterval that keeps running even when you close (not quit) the app. I would like to call a function when my app is closed or the device is put to sleep so that it clears the setInterval.

Answer

AppState is your friend! Have a look at the documentation of AppState.

So in your component, where the setTimeout exists, just require AppState and add an event listener like this:

AppState.addEventListener('background', this.handlePutAppToBackground);
AppState.addEventListener('inactive', this.handlePutAppToBackground);

handlePutAppToBackground() would be now a method in your component, where you would call clearTimeout(...)