From 7104c5ef3670807660708ce590b877a30f15e9ac Mon Sep 17 00:00:00 2001 From: Nedunchezhiyan-M Date: Tue, 20 Oct 2026 04:18:59 -0700 Subject: [PATCH] Add useAppState() hook for tracking app foreground/background state Summary: Add a new `useAppState()` React hook that lets components subscribe to app state changes, following the same pattern as the existing `useColorScheme()` and `useWindowDimensions()` hooks. ### Problem Currently, tracking app state requires manually managing AppState event listeners and local state: ```js // Before - verbose boilerplate function MyComponent() { const [appState, setAppState] = useState(AppState.currentState); useEffect(() => { const sub = AppState.addEventListener('change', setAppState); return () => sub.remove(); }, []); } ``` ### Solution A single-line hook using React's `useSyncExternalStore`: ```js // After - clean and simple import { useAppState } from 'react-native'; function MyComponent() { const appState = useAppState(); // Returns: 'active' | 'background' | 'inactive' | 'unknown' } ``` ### Common use cases for mobile apps - **Refresh data** when the app returns to foreground - **Pause/resume media** when the app is backgrounded - **Save drafts** when the user leaves the app - **Disable network polling** while in background to save battery - **Track analytics** for session foreground/background time ### What's included - `useAppState.js` - Hook implementation using `useSyncExternalStore` - `useAppState.d.ts` - TypeScript declarations - Export from `react-native` package (index.js + index.js.flow) - Jest mock for testing (`useAppState` returns `'active'` by default) - Unit tests following the `useColorScheme` test pattern ## Changelog: [GENERAL] [ADDED] - Add useAppState() hook for subscribing to app foreground/background state changes X-link: https://github.com/facebook/react-native/pull/56386 Reviewed By: javache Differential Revision: D100746279 Pulled By: Abbondanzo fbshipit-source-id: a8e41e8806eac1030636a0d0fd713fba732fe417 --- .../jest-preset/jest/mocks/useAppState.js | 15 +++ packages/jest-preset/jest/setup.js | 6 + .../AppState/__tests__/useAppState-itest.js | 127 ++++++++++++++++++ .../Libraries/AppState/useAppState.d.ts | 20 +++ .../Libraries/AppState/useAppState.js | 64 +++++++++ packages/react-native/ReactNativeApi.d.ts | 4 +- packages/react-native/index.js | 3 + packages/react-native/index.js.flow | 1 + 8 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 packages/jest-preset/jest/mocks/useAppState.js create mode 100644 packages/react-native/Libraries/AppState/__tests__/useAppState-itest.js create mode 100644 packages/react-native/Libraries/AppState/useAppState.d.ts create mode 100644 packages/react-native/Libraries/AppState/useAppState.js diff --git a/packages/jest-preset/jest/mocks/useAppState.js b/packages/jest-preset/jest/mocks/useAppState.js new file mode 100644 index 00000000000..bffb2c699ef --- /dev/null +++ b/packages/jest-preset/jest/mocks/useAppState.js @@ -0,0 +1,15 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import type {AppStateStatus} from 'react-native'; + +const useAppState = jest.fn(() => 'active') as JestMockFn<[], AppStateStatus>; + +export default useAppState; diff --git a/packages/jest-preset/jest/setup.js b/packages/jest-preset/jest/setup.js index cc29494c126..87049860fe3 100644 --- a/packages/jest-preset/jest/setup.js +++ b/packages/jest-preset/jest/setup.js @@ -93,6 +93,12 @@ mock( // $FlowFixMe[incompatible-type] - `./mocks/AppState` is incomplete. 'm#./mocks/AppState', ); +mock( + // $FlowFixMe[cannot-resolve-module] + 'm#react-native/Libraries/AppState/useAppState', + // $FlowFixMe[react-rule-hook-incompatible] + 'm#./mocks/useAppState', +); mock( // $FlowFixMe[cannot-resolve-module] 'm#react-native/Libraries/BatchedBridge/NativeModules', diff --git a/packages/react-native/Libraries/AppState/__tests__/useAppState-itest.js b/packages/react-native/Libraries/AppState/__tests__/useAppState-itest.js new file mode 100644 index 00000000000..4e08c2370ab --- /dev/null +++ b/packages/react-native/Libraries/AppState/__tests__/useAppState-itest.js @@ -0,0 +1,127 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; + +import View from '../../Components/View/View'; +import AppState, {type AppStateStatus} from '../AppState'; +import useAppState from '../useAppState'; +import * as Fantom from '@react-native/fantom'; +import * as React from 'react'; + +describe('useAppState', () => { + const originalAddEventListener = AppState.addEventListener; + const originalCurrentState = AppState.currentState; + + let observed: AppStateStatus | void; + + afterEach(() => { + // $FlowFixMe[cannot-write] + AppState.addEventListener = originalAddEventListener; + AppState.currentState = originalCurrentState; + observed = undefined; + }); + + function mockSubscription() { + const handlers: Array<(AppStateStatus) => void> = []; + const remove = jest.fn(); + const addEventListener = jest.fn( + (type: string, handler: AppStateStatus => void) => { + handlers.push(handler); + return {remove}; + }, + ); + // $FlowFixMe[cannot-write] + AppState.addEventListener = addEventListener; + return {addEventListener, handlers, remove}; + } + + function renderHook() { + function TestComponent() { + observed = useAppState(); + return ; + } + + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + return root; + } + + for (const state of ['active', 'background', 'inactive', 'extension']) { + it(`returns '${state}' when AppState reports '${state}'`, () => { + mockSubscription(); + AppState.currentState = state; + + const root = renderHook(); + + expect(observed).toBe(state); + + root.destroy(); + }); + } + + it("returns 'unknown' when the current state is not yet known", () => { + mockSubscription(); + AppState.currentState = null; + + const root = renderHook(); + + expect(observed).toBe('unknown'); + + root.destroy(); + }); + + it('subscribes to changes and re-renders with the new state', () => { + const {addEventListener, handlers} = mockSubscription(); + AppState.currentState = 'active'; + + const root = renderHook(); + + expect(addEventListener.mock.calls.length).toBe(1); + expect(addEventListener.mock.calls[0][0]).toBe('change'); + expect(typeof addEventListener.mock.calls[0][1]).toBe('function'); + expect(observed).toBe('active'); + + AppState.currentState = 'background'; + Fantom.runTask(() => { + handlers.forEach(handler => handler('background')); + }); + expect(observed).toBe('background'); + + root.destroy(); + }); + + it('unsubscribes when the component unmounts', () => { + const {remove} = mockSubscription(); + AppState.currentState = 'active'; + + const root = renderHook(); + expect(observed).toBe('active'); + + root.destroy(); + Fantom.runWorkLoop(); + + expect(remove).toHaveBeenCalledTimes(1); + }); + + it('throws when called outside of a component', () => { + let error; + try { + // $FlowFixMe[react-rule-hook] + useAppState(); + } catch (e) { + error = e; + } + + expect(error).toBeInstanceOf(Error); + }); +}); diff --git a/packages/react-native/Libraries/AppState/useAppState.d.ts b/packages/react-native/Libraries/AppState/useAppState.d.ts new file mode 100644 index 00000000000..abf529fe9b5 --- /dev/null +++ b/packages/react-native/Libraries/AppState/useAppState.d.ts @@ -0,0 +1,20 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import type {AppStateStatus} from './AppState'; + +/** + * `useAppState` is a React hook that returns the current app state. + * The component will re-render whenever the app state changes. + * + * Returns one of: 'active', 'background', 'inactive', 'unknown', or 'extension'. + * + * @see https://reactnative.dev/docs/appstate + */ +export default function useAppState(): AppStateStatus; diff --git a/packages/react-native/Libraries/AppState/useAppState.js b/packages/react-native/Libraries/AppState/useAppState.js new file mode 100644 index 00000000000..6edf8ae0d55 --- /dev/null +++ b/packages/react-native/Libraries/AppState/useAppState.js @@ -0,0 +1,64 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +'use strict'; + +import type {AppStateStatus} from './AppState'; + +import AppState from './AppState'; +import {useSyncExternalStore} from 'react'; + +const subscribe = (onStoreChange: () => void) => { + const subscription = AppState.addEventListener('change', onStoreChange); + return () => subscription.remove(); +}; + +const getSnapshot = (): AppStateStatus => { + const currentState = AppState.currentState; + return currentState === 'active' || + currentState === 'background' || + currentState === 'inactive' || + currentState === 'extension' + ? currentState + : 'unknown'; +}; + +/** + * `useAppState` is a React hook that returns the current app state. + * + * The value will be one of: + * - `active` - The app is running in the foreground + * - `background` - The app is running in the background + * - `inactive` - (iOS only) Transitioning between foreground and background + * - `unknown` - The initial state before the app state is determined + * + * The hook automatically subscribes to app state changes and re-renders the + * component when the state changes. + * + * Usage: + * ``` + * function MyComponent() { + * const appState = useAppState(); + * + * useEffect(() => { + * if (appState === 'active') { + * // App came to foreground - refresh data + * } + * }, [appState]); + * + * return App is {appState}; + * } + * ``` + * + * See https://reactnative.dev/docs/appstate + */ +export default function useAppState(): AppStateStatus { + return useSyncExternalStore(subscribe, getSnapshot); +} diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 9cc8048a3e7..89b0fe69edd 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<09cb4ee90e2e29b0924c0359d0ebef39>> + * @generated SignedSource<<29785e09db994cf0d43e7426f47c1b30>> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -5449,6 +5449,7 @@ declare function useAnimatedValueXY( }, config?: Animated.AnimatedConfig | null | undefined, ): Animated.ValueXY +declare function useAppState(): AppStateStatus declare function useColorScheme(): ColorSchemeName | null declare function usePressability( config: null | PressabilityConfig | undefined, @@ -6084,6 +6085,7 @@ export { useAnimatedColor, // 1faf88ce useAnimatedValue, // dc9d6f5c useAnimatedValueXY, // dc9057ea + useAppState, // 9338748a useColorScheme, // d585efdb usePressability, // af291ad3 useWindowDimensions, // bb4b683f diff --git a/packages/react-native/index.js b/packages/react-native/index.js index 79b601abb36..a86064115ca 100644 --- a/packages/react-native/index.js +++ b/packages/react-native/index.js @@ -383,6 +383,9 @@ module.exports = { get useAnimatedColor() { return require('./Libraries/Animated/useAnimatedColor').default; }, + get useAppState() { + return require('./Libraries/AppState/useAppState').default; + }, get useColorScheme() { return require('./Libraries/Utilities/useColorScheme').default; }, diff --git a/packages/react-native/index.js.flow b/packages/react-native/index.js.flow index 3d015144404..113127b308b 100644 --- a/packages/react-native/index.js.flow +++ b/packages/react-native/index.js.flow @@ -459,6 +459,7 @@ export type { EventHandlers as PressabilityEventHandlers, } from './Libraries/Pressability/Pressability'; export {default as usePressability} from './Libraries/Pressability/usePressability'; +export {default as useAppState} from './Libraries/AppState/useAppState'; export {default as useColorScheme} from './Libraries/Utilities/useColorScheme'; export {default as useWindowDimensions} from './Libraries/Utilities/useWindowDimensions'; export {default as UTFSequence} from './Libraries/UTFSequence';