공식 도큐먼트 AppState active
- The app is running in the foregroundbackground
- The app is running in the background. The user is either:in another app on the home screen [Android] on another Activity
(even if it was launched by your app) [iOS] inactive
- This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the Multitasking view or in the event of an incoming call
예시 코드 기존 상태가 inactive | background
이고 새로운 상태가 active
라면 포그라운드 전환 으로 인지 import React, { useRef, useState, useEffect } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";
const AppStateExample = () => {
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = useState(appState.current);
useEffect(() => {
AppState.addEventListener("change", _handleAppStateChange);
return () => {
AppState.removeEventListener("change", _handleAppStateChange);
};
}, []);
const _handleAppStateChange = (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
};
return (
<View style={styles.container}>
<Text>Current state is: {appStateVisible}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
export default AppStateExample;
예시코드2 어차피 change에 대해서만 잡으므로, change 되는 것이 ‘active’라면 back→fore 으로 가정할 수 있다. const handleListener = useCallback(
(state: AppStateStatus): void => {
if (state === 'active') {
console.log("App has come to the foreground!");
}
},
[handleVersionCheck],
);
useEffect(() => {
handleVersionCheck();
AppState.addEventListener('change', handleListener);
return (): void => {
AppState.removeEventListener('change', handleListener);
};
}, [handleVersionCheck, handleListener]);