Last active
August 1, 2019 06:49
-
-
Save srph/6fd12d42e5de8714727a7ad930dee9b7 to your computer and use it in GitHub Desktop.
React Hooks: Show something momentarily.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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