useTimeout
useTimeout manages a timeout that starts automatically on mount and can be controlled manually.
Usage
import { useState } from "react";
import { useTimeout } from "hookify-react";
export default function UseTimeoutExample() {
const [message, setMessage] = useState("Waiting...");
const { set, clear, reset } = useTimeout(() => {
setMessage("Timeout executed!");
}, 2000);
return (
<div>
<p>{message}</p>
<button onClick={set}>Start Timeout</button>
<button onClick={clear}>Clear Timeout</button>
<button onClick={reset}>Reset Timeout</button>
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
callback | () => void | - | The function to run when the timeout completes. |
delay | number | - | The delay in milliseconds before the callback runs. |
Return Value
useTimeout returns an object with the following methods:
| Property | Type | Description |
|---|---|---|
set | () => void | Starts the timeout, clearing any pending timer first. |
clear | () => void | Clears the timeout before it executes. |
reset | () => void | Resets the timeout by clearing the current one and starting a new one. |
Behavior
- Starts the timeout automatically on mount and whenever
delaychanges. setclears any pending timer before starting a new one, so timers never stack.- Always invokes the latest
callback, so it never needs to be memoized. - Clears the timeout automatically on unmount.