Skip to content

Instantly share code, notes, and snippets.

@ShizukuIchi
Last active July 5, 2020 01:13
Show Gist options
  • Save ShizukuIchi/7b74e280e59686a330ba9bd6f73fe22b to your computer and use it in GitHub Desktop.
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.
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
@michaeljohansen
Copy link

Tip: The useEffect should return a function that runs clear() to avoid a memory leak if the parent component is unmounted while the timeout runs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment