2.1.1 • Published 4 years ago

@react-hook/timeout v2.1.1

Weekly downloads
133
License
MIT
Repository
github
Last release
4 years ago

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]
ArgumentTypeDefaultRequired?Description
msnumber0NoThis 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]
ArgumentTypeDefaultRequired?Description
callback(...args: any[]) => voidundefinedYesThis is the callback you want to fire after the timeout duration is exceeded when start() is invoked.
msnumber0NoThis 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