h3/use's logo

h3/use

Command Palette

Search for a command to run...

useTimeout

Executes a callback after a specified delay.

useTimeout
This component demonstrates the useTimeout hook. Click start to trigger a timeout.

Click "Start" to begin the timeout.

Installation

Props

PropTypeDefaultDescription
callback() => void() => {}The function to execute after the delay.
delaynumber | nullnullThe delay in milliseconds before execution.

Key Features & Details

  • The hook sets a one-time timeout using setTimeout and cleans up with clearTimeout.
  • Passing null as delay cancels the timeout.
  • Ensures the latest callback is invoked by using a ref.

Examples

Basic Usage

import { useTimeout } from '@/registry/hooks/use-timeout';
 
function Component() {
  useTimeout(() => {
    console.log('timeout!');
  }, 2000);
 
  return <div>Check the console after 2 seconds.</div>;
}

Pause and Resume

import { useState } from 'react';
 
import { useTimeout } from '@/registry/hooks/use-timeout';
 
function TimeoutComponent() {
  const [active, setActive] = useState(true);
  const [message, setMessage] = useState('Waiting...');
 
  useTimeout(() => setMessage('Done!'), active ? 3000 : null);
 
  return (
    <div>
      <p>{message}</p>
      <button onClick={() => setActive((a) => !a)}>
        {active ? 'Pause' : 'Resume'}
      </button>
    </div>
  );
}