Created
July 14, 2024 11:23
-
-
Save smitroshin/a03aa30824201fa45f68e5b4532ba051 to your computer and use it in GitHub Desktop.
A normal setTimeout with automatic cleanup on unmount
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 { useCallback, useEffect, useRef } from "react" | |
/** | |
* A normal setTimeout with automatic cleanup on unmount | |
*/ | |
export const useSafeTimeout = () => { | |
const timeout = useRef<NodeJS.Timeout | null>(null) | |
const setSafeTimeout = useCallback((callback: () => void, ms: number) => { | |
timeout.current = setTimeout(callback, ms) | |
}, []) | |
useEffect(() => { | |
return () => { | |
if (timeout.current) clearTimeout(timeout.current) | |
} | |
}, []) | |
return setSafeTimeout | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment