75

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.

10
  • Looking for a solution too. Have you found something so far? Commented Sep 28, 2016 at 11:01
  • Hey did you find any solution?? Commented Jan 23, 2020 at 7:10
  • Have any solution yet ? Commented Jan 30, 2020 at 8:21
  • Unfortunately not yet, user888750's answer below is the closest we have atm Commented Jan 31, 2020 at 17:09
  • Its been 4 years, no solution yet?? Commented Sep 8, 2020 at 23:40

7 Answers 7

28

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>
    );
  }

}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the reply, but unfortunately this detects when the app is in the background or brought to the foreground, not closed
This doesn't answer the question at all. You can accomplish this, you just need to use a 3rd party library. Check out react-native-queue for more info: github.com/billmalarky/…
Inactive state is only available for iOS. Check all available states for each platform here: reactnative.dev/docs/appstate
4

With @react-native-community/hooks you can use the useAppState hook to check the app state.

When you close the app, it gets a state of unknown once you open it back. When is in background, it says background' or 'inactive'. So when it's unknown` you know the app is opening from being closed, not minimized or in the background.

1 Comment

It doesn't get the 'unknown' state.
2

I suggest to use web socket and it will help you to solve your problem, as following :

react native app

import React from 'react';
const io = require('socket.io-client/dist/socket.io');

const App = ()=>{
    React.useEffect(()=>{
        // connect to web socket
        window.appSocket = io.connect(`<server-origin>/?token=<string>&userAppId=<string>`);
        window.appSocket.on('connect',()=>{
            // do what you line
        })
    },[])

    ...
}
export default App; 

express server side

const express   = require('express');
const server    = express();
const http      = require('http').Server(server);
const io        = require('socket.io')(http);
io.on('connection',(socket)=>{ // this callback function for each web socket connection
    let { token , userAppId } = socket.handshake.query;
    if( userAppId ){ 
        console.log(`${userAppId} online`)
        socket.on('disconnect',(resean)=>{
            console.log(`${userAppId} shut down`)
        })
    }
});

for more details, you can check socket.io

Comments

0

Just ran into this same issue. The answer that's accepted does not actually do what is asked in the OP.

A hacky solution would be to set a flag on the first screen your application opens when opened fresh and to NOT SHOW THAT SCREEN when the app has just been backgrounded.

Not super elegant and I can't show example code, but it fixes my particular issue.

Comments

0

Looks like there is no solution to this as of now . The 'inactive' and 'background' states cannot be used to find kill state also. I think there is a reason we donot know when app is killed as it is done by iOS - it decides based on history and other factors so as to kill the app. Even if we close the app , the OS doesnt immediately kill the app it just goes to 'background' mode.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-1

My current workaround is to run the code when the app is launched instead. It's practically the other side of the same coin. Instead of trying to run as the app is being closed, run that code as the app is being launched next time.

// App.js
export default App() {
  useEffect(() => {
    // Run desired code here <----
    console.log("App is launching")
  }, [])

  return (
    <View>
      <Text>Hello world</Text>
    </View>
  )
}

Comments

-4

As a simple method , we can use componentWillUnmount() inside the root component for detect the app is closed. Because Root component Unmount only when app is closed. :)

3 Comments

This solution won't work as componentWillUnmount is not called when the app is terminated by user.
Are you sure about that ? Because i just check it again and it worked . ( Note : I mean componentWillUnmount method inside the App.js file ) :)
Did you tap the app switcher and then swiped to terminate the app? As far as I know, there is no way of knowing when the app is terminated by user as you can see in this link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.