useTimeoutWhen
Runs the latest callback once after a delay while a condition remains true.
About
useTimeoutWhen schedules one browser timeout while a condition is true. A separate key lets callers deliberately restart an otherwise unchanged timeout.
Examples
import { useState } from "react";
import { useTimeoutWhen } from "rooks";
export default function DelayedNotice() {
const [key, setKey] = useState(0);
const [message, setMessage] = useState("Waiting…");
useTimeoutWhen(() => setMessage("Ready"), 1000, true, key);
return (
<section>
<p role="status">{message}</p>
<button
type="button"
onClick={() => {
setMessage("Waiting…");
setKey((value) => value + 1);
}}
>
Restart
</button>
</section>
);
}Parameters
| Argument | Type | Default | Meaning |
|---|---|---|---|
callback | () => void | required | Latest function invoked by the timeout. |
timeoutDelayMs | number | 0 | Delay in milliseconds. |
when | boolean | true | Schedules while true. |
key | string | number | 0 | Changing it clears and restarts the timeout. |
Return value
The hook returns void.
Behavior and lifecycle
Changing the delay, condition, or key clears the pending timeout and evaluates scheduling again. Callback changes do not reset it because a fresh callback wrapper is used. Disabling or unmounting clears pending work. If an effect runs without window, the hook warns and schedules nothing. Callback exceptions are not caught.
Compatibility and accessibility
Effects do not run in server-rendered HTML. Browsers can clamp delayed timers and pause them in background tabs, so do not use this as a precise clock. Make delayed status changes perceivable, and give users control over time limits where accessibility requirements call for it.