Last active
July 5, 2020 01:13
-
-
Save ShizukuIchi/7b74e280e59686a330ba9bd6f73fe22b to your computer and use it in GitHub Desktop.
React hook generates a resettable setTimeout and only reset when reset is invoked.
This file contains 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, useEffect } from 'react' | |
const useResettableTimeout = (ms = 0, fn = () => {}, args = []) => { | |
const [timeout, setTimeoutVal] = useState(); | |
function start() { | |
setTimeoutVal(setTimeout(fn.bind(null, args), ms)); | |
return clear; | |
} | |
function clear() { | |
clearTimeout(timeout) | |
} | |
function reset() { | |
clear(); | |
return start(); | |
} | |
useEffect(start, []) | |
return reset; | |
} | |
export default useResettableTimeout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tip: The
useEffect
should return a function that runsclear()
to avoid a memory leak if the parent component is unmounted while the timeout runs.