@silicon.js/app-state
Version:
A lightweight React Native package for tracking and managing application state changes with a simple provider-based architecture.
41 lines (34 loc) • 1.06 kB
text/typescript
import { useEffect, useRef, useState } from 'react';
import { AppState, AppStateStatus } from 'react-native';
export interface UseAppStateProps {
initialCount?: number;
initialState?: AppStateStatus;
}
interface UseAppStateReturn {
count: number;
state: AppStateStatus;
}
export const useAppState = ({
initialCount = 0,
initialState = AppState.currentState,
}: UseAppStateProps = {}): UseAppStateReturn => {
const [count, setCount] = useState(initialCount);
const [currentAppState, setCurrentAppState] = useState<AppStateStatus>(initialState);
const appStateRef = useRef<AppStateStatus>(initialState);
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextAppState) => {
if (appStateRef.current !== nextAppState) {
appStateRef.current = nextAppState;
setCurrentAppState(nextAppState);
setCount((prevCount) => prevCount + 1);
}
});
return () => {
subscription.remove();
};
}, []);
return {
count: count + 1,
state: currentAppState,
};
};