React-native
[ React Native ] AppState foreground, background 상태 알기
부루붐
2023. 2. 9. 17:53
참고문서
https://reactnative.dev/docs/appstate.html
AppState · React Native
AppState can tell you if the app is in the foreground or background, and notify you when the state changes.
reactnative.dev
코드
import React, {useRef, useEffect} from 'react';
import {AppState, View} from 'react-native';
const TestContainer = () => {
const appState = useRef(AppState.currentState);
const handleAppStateChange = nextAppState => {
console.log('nextAppState', appState.current, nextAppState);
if (
appState.current.match(/inactive|background/) &&
nextAppState === 'active'
) {
console.log('is foreground!');
// foreground 진입시 실행됨
}
if (
appState.current.match(/inactive|active/) &&
nextAppState === 'background'
) {
console.log('Is background!');
// background 진입시 실행됨
}
appState.current = nextAppState;
};
useEffect(() => {
AppState.addEventListener('change', handleAppStateChange);
return () => {
AppState.removeEventListener('change', handleAppStateChange);
};
}, []);
return <View></View>;
}
export default TestContainer;