12

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.

0

3 Answers 3

8

itinance was close. The answer is actually to use

AppState.addEventListener('change', state => {
  if (state === 'active') {
    // do this
  } else if (state === 'background') {
    // do that
  } else if (state === 'inactive') {
    // do that other thing
  }
});
Sign up to request clarification or add additional context in comments.

4 Comments

This is only on iOS, doesnt work on Android
this does not fire when you close the app, only when you minimize it or change apps
did anyone find solution? 1) for android 2) does not fire when app close?
Is the callback in addEventListener running in react context then or outside of it? So basically, do I still have access to hooks?
6

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(...)

2 Comments

docs for AppState include no mention of closing the app. When you minimize the app, or change apps, it runs the background state -which handles that AppState. If you "close" an app -AppState fires no changes
does not works!
0

I solved this issue by adding useEffect() without dependencies to the component where i want to emit a certain event when the component unmounts for any reason and in the clean up function emit the desired function.

useEffect(() => {
 return () => {
  The desired function
 }
})

2 Comments

add an empty dependency array ([]) to this useEffect, otherwise the function in return will run on every render!
But is closing the app actually still unmounting the screen? I expect this to work on leaving a screen / closing a component.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.