Skip to content

Instantly share code, notes, and snippets.

@srph
Last active August 1, 2019 06:49
Show Gist options
  • Save srph/6fd12d42e5de8714727a7ad930dee9b7 to your computer and use it in GitHub Desktop.
Save srph/6fd12d42e5de8714727a7ad930dee9b7 to your computer and use it in GitHub Desktop.
React Hooks: Show something momentarily.
import { useState, useRef } from 'react'
import useUpdateEffect from 'react-use/lib/useUpdateEffect'
interface Props {
timeout: number
}
type Payload = [boolean, () => void]
function useBufferState(props: Props): Payload {
const [state, internalSetState] = useState(false)
const counterRef = useRef<number>(0)
const timeoutRef = useRef<number>(null)
function setState(): void {
++counterRef.current
internalSetState(false)
}
useUpdateEffect(() => {
internalSetState(true)
timeoutRef.current = window.setTimeout(() => {
internalSetState(false)
}, props.timeout)
return () => {
window.clearTimeout(timeoutRef.current)
}
}, [counterRef.current])
return [state, setState]
}
export {
useBufferState,
useBufferState as default
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment