Sometimes a mobile application needs to know when it becomes active or inactive. React Native provides the AppState API for this. There are several ways to use this API, including a new one that my colleagues and I just released.
In React Native, the
AppState API lets you check the current state of the application with
AppState.currentState. You can also add an event listener to be notified when the state changes.
Possible states include:
null: Initial value while the real state is being retrieved.
active: The app is running in the foreground.
background: The app is running in the background while the user is in another app or on the home screen.
inactive: The app is transitioning between foreground and background or otherwise inactive (such as when there’s an incoming call).
When you want to use an event listener, the normal approach is to use the React component lifecycle methods
componentWillUnmount along with an event handler to handle the change.
AppStateListener is a React component that takes three callback functions as props:
AppState signals a state change,
AppStateListener calls the appropriate callback, allowing your application to respond as necessary.
AppStateListener calls the
onActive callback when the component mounts and the
onBackground callback when it unmounts.
All three props are optional, so you only need to specify the props you care about.
As an example from one of our applications, we cache some state locally on the device but we want to refresh that state from the server whenever the application becomes active. Here’s the code for that:
In our case,
refreshState is a bound Redux action creator that does what we need, but it can be any function.
You can have several instances of
AppStateListener in your application at the same time, each responding to changes in a different way.
In general, I’ve found that my responses to AppState changes involve side effects, so responding to them in a reducer doesn’t normally work for me.
However, if your responses can be handled by reducers, or if you use something like redux-saga, this can be a really good approach. You can define a saga that watches for the AppState change actions and responds to them.
AppState API can be really useful in React Native applications, whether you use it directly or via a more convenient wrapper.