Last active
February 8, 2025 18:11
-
-
Save manix84/994b4c73a7cee3453e2a7c44973724c5 to your computer and use it in GitHub Desktop.
A react hook for setTimeout
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
| /** | |
| This code is licensed under the terms of the MIT license | |
| */ | |
| import { useEffect, useRef } from 'react'; | |
| export const useTimeout = (callback: () => void, delay: number): [() => void] => { | |
| const timeoutIdRef = useRef<number | null>(null); | |
| useEffect(() => { | |
| timeoutIdRef.current = window.setTimeout(callback, delay); | |
| return () => { | |
| if (timeoutIdRef.current !== null) { | |
| window.clearTimeout(timeoutIdRef.current); | |
| } | |
| }; | |
| }, [callback, delay]); | |
| const clearTimeout = () => { | |
| if (timeoutIdRef.current !== null) { | |
| window.clearTimeout(timeoutIdRef.current); | |
| timeoutIdRef.current = null; | |
| } | |
| }; | |
| return [clearTimeout]; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment