forked from react-native-community/hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseAppState.ts
30 lines (24 loc) · 804 Bytes
/
useAppState.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import {useEffect, useState} from 'react'
import {AppState, AppStateStatus} from 'react-native'
export function useAppState() {
const currentState = AppState.currentState
const [appState, setAppState] = useState(currentState)
useEffect(() => {
function onChange(newState: AppStateStatus) {
setAppState(newState)
}
const subscription = AppState.addEventListener('change', onChange)
return () => {
// @ts-expect-error - React Native >= 0.65
if (typeof subscription?.remove === 'function') {
// @ts-expect-error - need update @types/[email protected]
subscription.remove()
} else {
// React Native < 0.65
AppState.removeEventListener('change', onChange)
}
}
}, [])
return appState
}
export {AppStateStatus}