|
| 1 | +/** |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @flow strict-local |
| 8 | + * @format |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict'; |
| 12 | + |
| 13 | +import type {AppStateStatus} from './AppState'; |
| 14 | + |
| 15 | +import AppState from './AppState'; |
| 16 | +import {useSyncExternalStore} from 'react'; |
| 17 | + |
| 18 | +const subscribe = (onStoreChange: () => void) => { |
| 19 | + const subscription = AppState.addEventListener('change', onStoreChange); |
| 20 | + return () => subscription.remove(); |
| 21 | +}; |
| 22 | + |
| 23 | +const getSnapshot = (): AppStateStatus => { |
| 24 | + return AppState.currentState ?? 'unknown'; |
| 25 | +}; |
| 26 | + |
| 27 | +/** |
| 28 | + * `useAppState` is a React hook that returns the current app state. |
| 29 | + * |
| 30 | + * The value will be one of: |
| 31 | + * - `active` - The app is running in the foreground |
| 32 | + * - `background` - The app is running in the background |
| 33 | + * - `inactive` - (iOS only) Transitioning between foreground and background |
| 34 | + * - `unknown` - The initial state before the app state is determined |
| 35 | + * |
| 36 | + * The hook automatically subscribes to app state changes and re-renders the |
| 37 | + * component when the state changes. |
| 38 | + * |
| 39 | + * Usage: |
| 40 | + * ``` |
| 41 | + * function MyComponent() { |
| 42 | + * const appState = useAppState(); |
| 43 | + * |
| 44 | + * useEffect(() => { |
| 45 | + * if (appState === 'active') { |
| 46 | + * // App came to foreground - refresh data |
| 47 | + * } |
| 48 | + * }, [appState]); |
| 49 | + * |
| 50 | + * return <Text>App is {appState}</Text>; |
| 51 | + * } |
| 52 | + * ``` |
| 53 | + * |
| 54 | + * See https://reactnative.dev/docs/appstate |
| 55 | + */ |
| 56 | +export default function useAppState(): AppStateStatus { |
| 57 | + return useSyncExternalStore(subscribe, getSnapshot); |
| 58 | +} |
0 commit comments