React hook for managing asynchronous tasks with delay, repeat, and auto-restart support
npm install react-usetask-z

!Downloads
A lightweight React custom hook for creating flexible tasks/timers.
š¹ Supports sequential or fixed interval tasks
š¹ Repeat tasks a fixed number of times or infinitely
š¹ Cancel, reset, and auto-restart tasks
š¹ Works with async or sync functions
---
š Codesandbox Example
---
``bash`
npm install react-usetask-zor
yarn add react-usetask-z
Import in your project:
`ts`
import useTask from "react-usetask-z";
---
`ts`
const { execute, executeAsync, cancel, reset } = useTask({
fn: async () => {
console.log("ā” Task executed!");
},
delay: 1000, // Initial delay in ms
repeat: 5, // Repeat 5 times, true = infinite
interval: 500, // Interval between repeats in ms
mode: "sequential", // sequential | fixed
retry: 2, // retry 2 times on error
retryDelay: 1000, // 1s between retries
});
`ts`
execute();
`ts`
await executeAsync(async () => {
const response = await fetch("/api/data");
const data = await response.json();
console.log("ā
API completed", data);
});
`ts`
execute(() => console.log("ā± Run after 2 seconds"), 2000);
`ts`
cancel(); // š Stop current task
reset(); // š Reset repeat count and stop
- ā± sequential: waits for previous async task to complete before next iterationfixed
- ā” : runs tasks on a fixed interval regardless of previous task completion
`ts`
useTask({ mode: "fixed", interval: 1000 });
`ts`
useTask({
fn: () => console.log("š Restart task"),
repeat: 3,
restartDelay: 2000, // restart 2 seconds after completion
});
---
| Function | Description |
| ------------------------------------------------------ | -------------------------------------- |
| execute(fn?, delay?, repeat?, interval?, mode?) | ā” Run task (sync / normal callback) |executeAsync(fn?, delay?, repeat?, interval?, mode?)
| | ā
Run task async with promise support |cancel()
| | š Stop current task immediately |reset()
| | š Stop and reset repeat count |
---
- š If repeat is set to true, the task will loop infinitely until cancel() is calledexecuteAsync
- ā” Use if your task returns a promise and you want sequential executionrestartDelay
- ā
allows tasks to automatically restart after finishing all repeatsretry
- š Retry mechanism available with and retryDelayonError` callback
- š Error handling via
---
MIT