A custom React Native Hook that calculates the time an app spends in the inactive or background state. Ideal for handling operations when the app's state changes.
The useBackgroundTimer
is a custom React Native Hook that calculates the time spent by the app in the inactive or background state. This hook is very useful when you want to perform certain operations when the app goes to the background or becomes active again.
In the process of developing a mobile application, I found the need for a functionality that resets the app if it's inactive for 30 minutes. Upon researching, I found that the existing npm packages that provide similar functionality weren't maintained to my satisfaction. To address this gap and aid the community, I developed this hook. I hope it proves to be valuable to you.
This hook relies on react
, react-native
, and @react-native-async-storage/async-storage
. Make sure these dependencies are installed in your project.
npm install @react-native-async-storage/async-storage
or
yarn add @react-native-async-storage/async-storage
then
npm install rn-use-background-timer
or
yarn add rn-use-background-timer
First, import the >useBackgroundTimer hook in your component file.
import { useBackgroundTimer } from "rn-use-background-timer";
Then call useBackgroundTimer hook inside a functional component with or without the optional parameters.
const App = () => {
const { duration } = useBackgroundTimer();
// or
const { duration } = useBackgroundTimer({
keepPreviousTime: true,
onError: (error) => console.error(error),
onBackground: () => console.log("App went to background"),
onActive: () => console.log("App is now active"),
});
return (
<View>
<Text>App has been in background for {duration} seconds</Text>
</View>
);
};
The useBackgroundTimer
hook accepts an optional object as argument with the following properties:
keepPreviousTime: boolean
: Whether or not to keep the duration from the previous inactive or background state. Defaults tofalse
.onError: (error: Error) => void
: Function to execute when there is an error. Defaults toconsole.error
.onBackground: () => void
: Function to execute when app goes to the background state.onActive: () => void
: Function to execute when app becomes active.
This hook returns an object with the following property:
duration: number
: Time in seconds that the app spent in the inactive or background state.