React Native: setTimeout not working when app is backgrounded

Viewed 646

In React Native, when setTimeout is used to schedule execution of callback and then app is backgrounded, callback is never executed.

Why is that?

I did find several secondary sources which mention this behavior but no comprehensive docs.

1 Answers

Use the AppState event listener provided by react-native :-

  useEffect(() => {
    const subscription = AppState.addEventListener("change", nextAppState => 
  {
      if (
        appState.current.match(/inactive|background/) 
      ) {
         setTimeout(()=>{
          // your callback function
         },1000)
      }

    
    });

    return () => {
      subscription.remove();
    };
  }, []);

Here's the link to docs - https://reactnative.dev/docs/appstate

Related