Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Created July 14, 2024 11:23
Show Gist options
  • Save smitroshin/a03aa30824201fa45f68e5b4532ba051 to your computer and use it in GitHub Desktop.
Save smitroshin/a03aa30824201fa45f68e5b4532ba051 to your computer and use it in GitHub Desktop.
A normal setTimeout with automatic cleanup on unmount
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