mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
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
This commit is contained in:
1 parent
e10d6ba3a6
commit
7104c5ef36
8 files changed
+239
-1
No files matched your search
@@ -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;
|
||||
@@ -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',
|
||||
|
||||
@@ -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 <View />;
|
||||
}
|
||||
|
||||
const root = Fantom.createRoot();
|
||||
Fantom.runTask(() => {
|
||||
root.render(<TestComponent />);
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
@@ -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 <Text>App is {appState}</Text>;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* See https://reactnative.dev/docs/appstate
|
||||
*/
|
||||
export default function useAppState(): AppStateStatus {
|
||||
return useSyncExternalStore(subscribe, getSnapshot);
|
||||
}
|
||||
+3
-1
@@ -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
|
||||
|
||||
Vendored
+3
@@ -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;
|
||||
},
|
||||
|
||||
@@ -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';
|
||||
|
||||
Reference in new issue
Block a user