In React Native we have a method called AppState which detects the current state of the app whether in the background or foreground (active or inactive).

We can use useEffect and useState hooks to manage the app state and perform side effects, whether mounting or unmounting the component.
For this to take effect, we need to subscribe to an event listener called inside useEffect hook, allowing us to mount or unmount the app according to its current state.

The below code shows how we can achieve this:

import React, { useState, useEffect } from 'react';
import { AppState, View } from 'react-native';

const MyAppStateComponent = () => {
  const [appState, setAppState] = useState(AppState.currentState);
  const [isMounted, setIsMounted] = useState(true);

  const handleAppStateChange = (nextAppState) => {
    if (appState.match(/inactive|background/) && nextAppState === 'active') {
      setIsMounted(true);
    } else if (appState === 'active' && nextAppState.match(/inactive|background/)) {
      setIsMounted(false);
    }
    setAppState(nextAppState);
  };

  useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange);
    return () => {
      AppState.removeEventListener('change', handleAppStateChange);
    };
  }, []);

  return (
    <View>
      {isMounted && <Text>My My App State Component</Text>}
    </View>
  );
};

export default MyAppStateComponent;

In the above code, we used the useState hook to manage the app state and the mounting or unmounting of the app.

The useEffect hook manages the subscription and removal of the event listener in accordance with the app state change, which is managed by the isMounted useState variable. Removing the listener will also help avoid memory leaks in the app.

The handleAppStateChange function updates the isMounted variable’s state whenever the app state gets changed.

For More Information: ReactNative AppState

Support On Demand!

                                         
React Native