-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathuseAppState.ts
More file actions
45 lines (39 loc) · 1.34 KB
/
useAppState.ts
File metadata and controls
45 lines (39 loc) · 1.34 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { useEffect, useRef } from "react"
import { AppState, AppStateStatus } from "react-native"
/**
* Hook that returns app state, and takes a callback that is called on active state changes
*
* @param callback If defined, it will be called with the "activating" parameter = true when entering active state,
* false when leaving active state
*
* @returns one of 'active', 'background', 'inactive', or 'unknown'
*/
export const useAppState: (callback?: (activating: boolean) => void) => AppStateStatus = (
callback = undefined,
) => {
const callbackRef = useRef<typeof callback>()
useEffect(() => {
callbackRef.current = callback
}, [callback])
const appState = useRef(AppState.currentState)
useEffect(() => {
const cb = (activating: boolean) => callbackRef.current && callbackRef.current(activating)
const subscription = AppState.addEventListener("change", (nextAppState) => {
// Foregrounding
if (cb && appState.current !== "active" && nextAppState === "active") {
const result = true
cb(result)
}
// Backgrounding
if (cb && appState.current === "active" && nextAppState !== "active") {
const result = false
cb(result)
}
appState.current = nextAppState
})
return () => {
subscription.remove()
}
}, [callback])
return appState.current
}