23

When an Android App is sent to the background, it can persist its instance state in case it gets killed due to low memory (see Activity:onSaveInstanceState() and the bundle argument for Activity:onCreate(Bundle savedInstanceState)).

The default Activity behaviour is saving the state of the view hierarchy so for a lot of cases you don't have to write any code and it "just works"[tm].

Now for react-native this is not true. React native apps are hosted in a single MainActivity and their state is contained in the javascript interpreter in the app.

I created a sample repository with short documentation how to reproduce my problem here: https://github.com/einvalentin/react-native-state-test

I would want react-native to hook into the native android app state serialisation mechanism while providing application developers hooks to extend if they need custom serialisation. Alternatively I could see myself extending the MainActivity to forward the lifecycle events to the Javascript layer and do some custom state serialisation manually there - but this feels a bit clunky.

Is there an obvious way I have overlooked to save the state in react-native so that apps that are killed in the background are not restarted from scratch? This can always happen for example on low memory devices receiving a phone call while interacting with your app.

Thanks a lot!

Valentin
  • 2,066
  • 3
  • 18
  • 14
  • Did you ever figure out a good solution to this, @Valentin? Struggling with the same thing. Native Android handles this quite well where as React Native just wipes your stack and starts over from scratch. We played around with https://reactnavigation.org/docs/en/state-persistence.html but it's limited. – Joshua Pinter May 05 '19 at 20:43

1 Answers1

14

If you are using Redux for state management you should probably use redux-persist. If not you have a couple of different options:

wmcbain
  • 1,099
  • 9
  • 16
  • Thanks! So that would basically boil down to me sending onSaveInstanceState() & the iOS State Preservation & Restoration hooks down to react-native and persist the redux store. – Valentin Feb 21 '17 at 09:30
  • If you're using redux, just use redux-persist. Would appreciate an accepted answer. ;) – wmcbain Feb 21 '17 at 13:10