useTimeout
A React hook for creating declarative timeouts with automatic cleanup. Under the hood, it uses the setTimeout API.
- Installation
- Add Source Code
npm install @plenty-hooks/use-timeout
npx @plenty-hooks/cli use-timeout
Using this command will add the source code of the hook directly to your project.
Options:
--pathor-p: Specify the directory where the hook file should be saved--kebab-caseor-k: Use kebab-case for the output filename (e.g.,use-document-title.ts). By default, the filename uses camelCase (e.g.,useDocumentTitle.ts)
Note: By adding the source code of the hook directly to your project, you won't be able to install further updates automatically. You are on your own for maintaining and updating the code.
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. Passnullorundefinedto cancel the timeout.
Returns
void- This hook does not return any value.