rn-use-background-timer

1.0.5 • Public • Published

useBackgroundTimer

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.

Table of Contents

Intro

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.

Motivation

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.

Installation

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

Usage

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>
  );
};

API

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 to false.
  • onError: (error: Error) => void: Function to execute when there is an error. Defaults to console.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.

Package Sidebar

Install

npm i rn-use-background-timer

Weekly Downloads

2

Version

1.0.5

License

ISC

Unpacked Size

19.4 kB

Total Files

7

Last publish

Collaborators

  • kurucaner