카테고리 없음

[React Native] AppState / detect foreground, background

안다희 2020. 5. 21. 17:18
728x90

0. 소개

AppState를 이용하면 앱이 background였다가 foreground 상태로 왔는지, 그 반대인지를 알 수 있다. 

 

1. 문서

https://reactnative.dev/docs/appstate.html

 

React Native · A framework for building native apps using React

A framework for building native apps using React

reactnative.dev

 

2. Usage

앱이 포그라운드 -> 백그라운드 로 가는 순간

appState는 active -> inactive -> background로 바뀐다. 이 과정에서 앱이 백그라운드 상태가 되면 setAppState가 매끄럽게 이어져서 appState는 background여야 하는데, 그러지 않고 앱이 백그라운드에 있어도 appState는 active이다. useState로 렌더가 다시 되면서 state가 꼬이는 모양이다..

그래서 useRef를 사용했다. 렌더링과 상관없이 값만 바꿔주기 때문에 혼란이 없어진다.

 

 

import React, {useRef} from 'react';
import {AppState} from 'react-native';

export default () => {
  const appState = useRef(AppState.currentState);

  const handleAppStateChange = nextAppState => {
    console.log('⚽️appState nextAppState', appState.current, nextAppState);
    if (
      appState.current.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('⚽️⚽️App has come to the foreground!');
    }
    if (
      appState.current.match(/inactive|active/) &&
      nextAppState === 'background'
    ) {
      console.log('⚽️⚽️App has come to the background!');
    }
    appState.current = nextAppState;
  };

  useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange);
    return () => {
      AppState.removeEventListener('change', handleAppStateChange);
    };
  }, []);
}

 

 

이제 백그라운드와  포그라운드로 진입할 때 원하는 동작을 하면 된다!

 

 

 

 

** 틀린 부분이 있다면 댓글로 알려주세요!

** 공감과 댓글은 저에게 아주 큰 힘이 됩니다!