Where is it best to implement listening for AppState Change in a React Native App

  javascript, mobile, react-native

I have this service (modified from the RN Docs)

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

const useAppState = () => {
    const appState = useRef(AppState.currentState);
    const [appStateVisible, setAppStateVisible] = useState(appState.current);

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

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

            appState.current = nextAppState;
            setAppStateVisible(appState.current);
            console.log('AppState', appState.current);
        }
    };

    return {
        appStateVisible,
        handleAppStateChange: _handleAppStateChange
    }
};

export default useAppState;

This tells me the state of the App (foreground, background, …).
However, I wonder where to best implement this. Lets say I have six screens, do I have to add this on each and every screen in order to recoginze AppState changes? Because when the component where I call appState() gets unmounted, the listener also gets "lost". I am looking for a "global" way to add appState() only once, so that once the App is running, I always receive information about the App state, no matter on which screen/component I am looking at.

Source: Ask Javascript Questions

LEAVE A COMMENT