たまに必要になって毎回調べるので忘備録。
react-native でモバイルアプリを作成するとき、Web サイトと違うのは、「アプリを開く度、毎回 Component が mount されるわけではない」という事。同じく、アプリをbackgroundに持っていった時に unmount もされない。
例えば、ユーザーがアプリを開いている状態でホームボタンを押しても unmount 処理は行われないし、その後またアプリを foreground に戻したとき、react の再 render は行われないので mount 処理も行われない。
ユーザーが foreground に戻ってきたときにログインの session が切れているかどうかを確認したいと言ったときに、上記の理由から、useEffect だけで session をチェックすると言うことは厳しい。
その代わり、react-native は AppState という API を用意している。
import {AppState} from 'react-native'
これは、アプリが foreground であれば active
、background にあれば background
という状態を持つ。
iOS であれば、タスク一覧画面など、アプリがforegroundでもbackgroundでもない状態として inactive
という状態もある。
AppState には以下のように EventListener を設けて、AppState が変更した際に処理を追加することができる。
// ref: https://reactnative.dev/docs/appstate
import React, { useEffect } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";
const AppStateExample = () => {
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!");
}
console.log("AppState", appState.current);
};
...
};
「ユーザーがアプリを開いた時」というのは、毎回未起動時から入るか、backgroundからforegroundに変わる時か、わからないので、「ユーザーがアプリを開いた時」に毎回処理を挟みたいと言う場合は、AppStateを使うのが良い。