Last active
November 5, 2020 01:07
-
-
Save takumifukasawa/3785ae0f80845f76eb9664b45784e28b to your computer and use it in GitHub Desktop.
React: manage window timeout custom hooks
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 { useEffect, useRef } from "react"; | |
/** | |
* manage window timeout hooks | |
* | |
* ex) | |
* | |
* const [beginTimer, clearTimer] = useTimeout(() => { ... }, ms); | |
* | |
* useEffect(() => { | |
* beginTimer(); | |
* }, [deps1]); | |
* | |
* useEffect(() => { | |
* clearTimer(); | |
* }, [deps2]); | |
* | |
* @export | |
* @param {() => void | null} exec | |
* @param {number} ms | |
* @returns | |
*/ | |
export default function useTimeout( | |
exec: (() => void) | null, | |
ms: number | |
): [() => void, () => void] { | |
const timerId = useRef<number | null>(null); | |
const clearTimer = () => { | |
if (timerId.current) { | |
window.clearTimeout(timerId.current); | |
timerId.current = null; | |
} | |
}; | |
const beginTimer = () => { | |
clearTimer(); | |
timerId.current = window.setTimeout(() => { | |
if (exec) { | |
exec(); | |
} | |
clearTimer(); | |
}, ms); | |
}; | |
useEffect(() => { | |
return () => clearTimer(); | |
}, []); | |
return [beginTimer, clearTimer]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment