Skip to main content

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

ParameterTypeDefaultDescription
callback() => void-The function to run when the timeout completes.
delaynumber-The delay in milliseconds before the callback runs.

Return Value

useTimeout returns an object with the following methods:

PropertyTypeDescription
set() => voidStarts the timeout, clearing any pending timer first.
clear() => voidClears the timeout before it executes.
reset() => voidResets the timeout by clearing the current one and starting a new one.

Behavior

  • Starts the timeout automatically on mount and whenever delay changes.
  • set clears 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.