How to detect when a React Native app is closed (not suspended)?

Dale_Plante picture Dale_Plante · Aug 15, 2016 · Viewed 25.4k times · Source

I have looked everywhere and cannot find an answer to this. How can I detect when a user is trying to close my React Native app (as in the process is running, and they manually manage their apps and force exit it). I would like to add logout functionality when this happens, however cannot find a way to detect it. AppState appears to only detect when the app is brought in and out of the background.

Answer

user888750 picture user888750 · Jun 12, 2017

Looks like you can detect the previous state and compare it to the next state. You can't detect that the app is closing vs going into the background, from what I can find online, but you can detect if it was inactive (closed), or in the background.

Example from React Native Docs

import React, {Component} from 'react'
import {AppState, Text} from 'react-native'

class AppStateExample extends Component {

  state = {
    appState: AppState.currentState
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
    }
    this.setState({appState: nextAppState});
  }

  render() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }

}