Search code examples
react-nativeandroid-lifecyclelifecycleios-lifecycle

React Native lifecycle and restarts


Firstly, apologies for the slightly open ended questions but I can't find the info I'm looking for in other questions.

I'm trying to understand the lifecycle of a RN app on both iOS and Android. I understand the app bootstraps when you first start it and stays running while the phone is alive, but what happens when the user switches to a different app and comes back, or their screen times out then they switch it back on? It would be really annoying if the app restarted just because they briefly switched to check their email.

My specific use case (not particularly important to this generic question but included for context) is that I'm trying to build a game with socket.io connections and I'm wondering if I can hook into events to see if the app has been in the background or if I even need to. I have found a way of forcing a restart which may be necessary at some points, but I'd rather just try to reconnect things that have disconnected if I can find out when that happens.

Any push in the right direction would be appreciated.


Solution

  • The app doesn't restart when it goes in the background as you describe. The app keeps its state and the user sees the last screen they visited.

    You should have a look at react native's AppState https://facebook.github.io/react-native/docs/appstate

    Using AppState you can addEventListeners that capture the change of the app's state like when going to background.

    Of course there are also some problems here...

    1. You can't capture the "kill "event. You can only detect if the app is sent to the background but unfortunately you can't detect when the user chooses to "kill" the app
    2. You can't run any code while your app is in the background. This might be serious in your case but you should evaluate it. For example if you have a timer and you sent the app to the background then the timer stops.