NoteThe timer will not be scheduled if the delay is null. This is useful for conditionally enabling the timeout based on specific logic.
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.
| Name | Type | Description |
|---|---|---|
| callback | () => void | The function to be executed once the delay expires. |
| options.delay | number | null | Time in milliseconds before execution. If null, the timeout is disabled. |
| options.startOnMount | boolean | If true, the timer starts as soon as the component mounts. Default: true. |
| Name | Type | Description |
|---|---|---|
| cancel | () => void | Clears the pending timeout and sets isActive to false. |
| isActive | boolean | A reactive boolean indicating if a timer is currently counting down. |
| reset | () => void | Cancels any current timer and starts a fresh one from zero. |
| start | () => void | Manually triggers the timeout logic. |