I'm using hooks for updating state. in my code I have an AppState event listener and whenever it triggers I'm updating the appState using setAppState, however the appState inside the event listener did not change. but the value is updating outside the listener. can anyone explain why is behaving like that?
Here is my code:
import React, { FunctionComponent, useEffect, useState } from "react"
import { View, AppState, AppStateStatus } from "react-native"
const Test: FunctionComponent<any> = (props: any) => {
const [appState, setAppState] = useState < AppStateStatus > (AppState.currentState)
useEffect(() => {
AppState.addEventListener("change", _handleAppStateChange)
},[])
const _handleAppStateChange = (nextAppState: AppStateStatus) => {
//appState not Changing here
console.log(appState, "app state")
if (appState.match(/inactive|background/) && nextAppState === "active") {
console.log("App has come to the foreground!")
activateRealtime()
} else if (appState === "active" && nextAppState.match(/inactive|background/)) {
console.log("App has come to background!")
}
setAppState(nextAppState)
}
//appState updated here
console.log(appState, "app state")
return <View />
}
const [appState, setAppState] = useState < AppStateStatus > AppState.currentState
– OdetteodeumsetAppState(nextAppState)
is the last call within the function. – GustysetAppState(nextAppState)
since it'll only log state from the current render cycle. – GustynextAppState
. – BlowhardappState
in an effect, i.e.useEffect(() => console.log(appState, "app state"), [appState]);
since this will be the updated state or just lognextAppState
in the callback since that is what you will update state to anyway. – GustyappState
) never updates? – GustyState updates are asynchronous.
even though that is true, saying that will cause people to tryawait setState
. Also the main problem with setting state created with useState in functional components is stale closures – Comprise