import { useLatestRef } from "@vortexlabs/vortex-native";
import React from "react";
import { AppState } from "react-native";
export const useAppForeground = (onForeground: () => void) => {
const callbackRef = useLatestRef(onForeground);
React.useEffect(() => {
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") callbackRef.current();
});
return () => subscription.remove();
}, [callbackRef]);
};Features
- Keeps the same ref object across renders.
- Updates
.currentafter a committed value change. - Keeps values available to listeners and delayed callbacks.
Pass a value and read it through .current. Ref updates do not trigger renders; use state for visible UI.
Keeping a Callback Current
The subscription above is created once, because the ref object never changes. Each AppState change still calls the newest onForeground, so callers can pass an inline function without resubscribing.
Commit Timing
.current updates in a layout effect after the value changes, before your effects run. During render it still holds the previous value, so read it in effects, listeners, and timers.