useTimeout

A declarative hook for setTimeout.

Overview

useTimeout is a declarative wrapper around setTimeout. It allows you to trigger a callback after a specified delay, with automatic cleanup on unmount.

Demo

Delayed Action

Bomb Defusal

A demonstration of useTimeout. Defuse the bomb before the timeout fires!

💣
System Ready

API Reference

function useTimeout(callback: () => void, delay: number | null): void

Parameters

NameTypeDescription
callback() => voidFunction to execute after delay.
delaynumber | nullDelay in milliseconds. Pass null to cancel/pause.

Usage Example

import { useState } from 'react'
import { useTimeout } from 'react-hooks-ts'
 
function DelayedMessage() {
  const [visible, setVisible] = useState(true)
 
  useTimeout(() => {
    setVisible(false)
  }, 5000)
 
  return visible ? <div>I will disappear in 5s</div> : null
}