Explore Library
Code Quiz

AppState Foreground Detection Cleanup

Spot the subscription cleanup bug in a React Native AppState foreground/background listener.

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

export function useOnForeground(onForeground: () => void) {
  const appState = useRef<AppStateStatus>(AppState.currentState);

  useEffect(() => {
    const subscription = AppState.addEventListener('change', (next) => {
      if (appState.current.match(/inactive|background/) && next === 'active') {
        // cold/warm resume -> refresh data, revalidate session
        onForeground();
      }
      appState.current = next;
    });

    return () => {
      AppState.removeEventListener('change', subscription);
    };
  }, [onForeground]);
}

This hook should fire onForeground when the app returns from background, but it has a lifecycle bug. What is wrong?