useTimeout

A declarative React hook for managing the lifecycle of single-execution timers with manual controls and SSR safety.

Note

The timer will not be scheduled if the delay is null. This is useful for conditionally enabling the timeout based on specific logic.

Installation

bash

Description

The useTimeout hook provides a structured way to handle setTimeout within React components. By using a persistent reference for the callback, it avoids common pitfalls like stale closures or unexpected re-executions during re-renders. It offers a reactive isActive state and granular control methods (start, cancel, reset), ensuring that timers are cleaned up automatically when the component unmounts.

Parameters

NameTypeDescription
callback() => voidThe function to be executed once the delay expires.
options.delaynumber | nullTime in milliseconds before execution. If null, the timeout is disabled.
options.startOnMountbooleanIf true, the timer starts as soon as the component mounts. Default: true.

Return values

NameTypeDescription
cancel() => voidClears the pending timeout and sets isActive to false.
isActivebooleanA reactive boolean indicating if a timer is currently counting down.
reset() => voidCancels any current timer and starts a fresh one from zero.
start() => voidManually triggers the timeout logic.

Demo

Timeout

No changes detected.

Source code

tsx