react-usetask-z
v1.0.0
Published
React hook for managing asynchronous tasks with delay, repeat, and auto-restart support
Maintainers
Readme
react-usetask-z
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
🚀 Live Demo
📦 Installation
npm install react-usetask-z
# or
yarn add react-usetask-zImport in your project:
import useTask from "react-usetask-z";🛠 Usage
Initialize a task
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
});Run task immediately
execute();Run async task with await
await executeAsync(async () => {
const response = await fetch("/api/data");
const data = await response.json();
console.log("✅ API completed", data);
});Run after custom delay
execute(() => console.log("⏱ Run after 2 seconds"), 2000);Stop or reset tasks
cancel(); // 🛑 Stop current task
reset(); // 🔄 Reset repeat count and stopSequential vs Fixed mode
- ⏱
sequential: waits for previous async task to complete before next iteration - ⚡
fixed: runs tasks on a fixed interval regardless of previous task completion
useTask({ mode: "fixed", interval: 1000 });Auto-restart
useTask({
fn: () => console.log("🔄 Restart task"),
repeat: 3,
restartDelay: 2000, // restart 2 seconds after completion
});⚙️ API
| 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 |
✨ Notes
- 🔁 If
repeatis set totrue, the task will loop infinitely untilcancel()is called - ⚡ Use
executeAsyncif your task returns a promise and you want sequential execution - ✅
restartDelayallows tasks to automatically restart after finishing all repeats - 🔄 Retry mechanism available with
retryandretryDelay - 🛠 Error handling via
onErrorcallback
📋 License
MIT
