useTimeout
Update value after a given time
useTimeout provides a reactive pending state that flips from true to false after a specified delay. It returns a tuple of [isPending, start, cancel], giving you both a declarative status value and imperative controls. By default, the timer starts immediately on mount, but you can configure it to start manually via the immediate option.
When to Use
- Showing a loading indicator or splash screen for a minimum duration before revealing content
- Implementing auto-dismiss behavior for notifications, toasts, or banners after a fixed time
- Creating timed UI state transitions (e.g., disabling a button for a cooldown period)
Notes
- Immediate by default: The timer starts automatically on mount. Pass
{ immediate: false }to require an explicitstart()call. - Restartable: Calling
start()resets and restarts the timer. Callingcancel()stops it and keepsisPendingat its current value. - See also
useTimeoutFnfor executing a callback after a delay instead of toggling a boolean state, anduseIntervalfor repeated execution.
Usage
Live Editor
function Demo() { const [isPending, start, cancel] = useTimeout(5000); return ( <div> <div>Pending: {JSON.stringify(isPending)}</div> <button onClick={() => { start(); }} > Start Again </button> <button onClick={() => { cancel(); }} > Cancel </button> </div> ); };
Result
API
useTimeout
Returns
Stoppable: A tuple with the following elements:
- Whether to wait for the timer to execute.
- Set timer.
- Cancel timer.
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| ms | wait time | number | undefined | - |
| options | - | UseTimeoutOptions | undefined | - |
UseTimeoutOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| immediate | Start the timer immediate after calling this function | boolean | true |