Skip to main content

useTimeout

A React hook for creating declarative timeouts with automatic cleanup. Under the hood, it uses the setTimeout API.

React 19.2.0
npm install @plenty-hooks/use-timeout

Showcase

import { useState } from 'react';
import useTimeout from '@plenty-hooks/use-timeout';

function DelayedMessage() {
const [message, setMessage] = useState('');
const [delay, setDelay] = useState<number | null>(null);

useTimeout(() => {
setMessage('Hello after 2 seconds!');
}, delay);

return (
<div>
<p>{message || 'Click start to see message after 2 seconds'}</p>
<button onClick={() => setDelay(2000)}>Start</button>
<button onClick={() => setDelay(null)}>Cancel</button>
</div>
);
}

API

useTimeout(callback, delay)

Creates a timeout that calls the provided callback function after the specified delay. The timeout automatically cleans up when the component unmounts or when the delay changes.

Parameters

  • callback: () => void - The function to be called after the specified delay.
  • delay: number | null | undefined - The delay in milliseconds before the callback is invoked. Pass null or undefined to cancel the timeout.

Returns

  • void - This hook does not return any value.