useTimeout()
npm i @react-hook/timeout
A React hook that executes a callback after a timeout ms have been exceeded and the timeout has been started
Quick Start
import {useEffect} from 'react'
import {useTimeout, useTimeoutCallback} from '@react-hook/timeout'
// useTimeout() example
const Copy = ({text, resetAfterMs = 500}) => {
const [copied, copy] = useCopy(text)
const [timedOut, startTimeout, resetTimeout] = useTimeout(resetAfterMs)
// Reset the timeout any time text changes
useEffect(() => resetTimeout, [text, resetTimeout])
// Start the timeout when copied
useEffect(() => {
if (copied) {
startTimeout()
}
}, [startTimeout, copied])
return <input onClick={copy} value={text} />
}
// useTimeoutCallback() example
// This is the exact code useTimeout() uses
const useTimeoutClone = (ms) => {
const [timedOut, setTimedOut] = useState(false)
const [start, reset] = useTimeoutCallback(() => setTimedOut(true), ms)
return [timedOut, start, reset]
}
API
function useTimeout(ms = 0): [boolean, () => void, () => void]
Argument | Type | Default | Required? | Description |
---|---|---|---|---|
ms | number |
0 |
No | This is the timeout duration in milliseconds. When this threshold has been reached after start() has been invoked, timedOut will be true . If this value is 0 the hook will never timeout. |
Returns [timedOut: boolean, start: () => void, reset: () => void]
function useTimeoutCallback(
callback: (...args: any[]) => any,
ms = 0
): [() => void, () => void]
Argument | Type | Default | Required? | Description |
---|---|---|---|---|
callback | (...args: any[]) => void |
undefined |
Yes | This is the callback you want to fire after the timeout duration is exceeded when start() is invoked. |
ms | number |
0 |
No | This is the timeout duration in milliseconds. When this threshold has been reached after start() has been invoked, timedOut will be true . If this value is 0 the hook will never timeout. |
Returns [start: () => void, reset: () => void]
LICENSE
MIT