Is it possible to know if a RN app has gone to background? Any callback or trigger?

If I listen to componentDidUnmount or componentWillUnmount of the screen I'm on, it will only be fired if I go back/forth to another screen

3

Best Answer


You can listen to the appState event.From https://facebook.github.io/react-native/docs/appstate.html:

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

By the way, this will always say 'Current state is: active', because that is the only state in which the app will be visible for the user.

You can use the AppState:

App States

  • active - The app is running in the foreground
  • background - The app is running in the background. The user is either in another app or on the home screen
  • inactive - This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the Multitasking view or in the event of an incoming call

AppState.removeEventListener seems like deprecated, so I did this:

import React from 'react'import { AppState } from 'react-native'class AppStateClassComponent extends React.PureComponent {constructor(props){super(props)this.state = {appState: ''}this.onAppStateChange = (nextAppState) => {if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {console.log('App has come to the foreground!')}this.setState({ appState: nextAppState });}this.app_state = null}componentDidMount() {this.permission_check()if(this.app_state === null){this.app_state = AppState.addEventListener('change', this.onAppStateChange)}}componentWillUnmount() {if(this.app_state !== null){this.app_state?.remove()this.app_state = null}}render() {return (<Text>Current state is: {this.state.appState}</Text>)}}