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
👉 Codesandbox Example
📦 Installation
npm install react-usetask-z
yarn add react-usetask-z
Import 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,
repeat: 5,
interval: 500,
mode: "sequential",
retry: 2,
retryDelay: 1000,
});
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();
reset();
Sequential 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,
});
⚙️ API
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
repeat is set to true, the task will loop infinitely until cancel() is called
- ⚡ Use
executeAsync if your task returns a promise and you want sequential execution
- ✅
restartDelay allows tasks to automatically restart after finishing all repeats
- 🔄 Retry mechanism available with
retry and retryDelay
- 🛠 Error handling via
onError callback
📋 License
MIT