Skip to content

Instantly share code, notes, and snippets.

@andreydro
Last active September 18, 2021 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreydro/aca2f37287506ba7dc4651cb6ed1d210 to your computer and use it in GitHub Desktop.
Save andreydro/aca2f37287506ba7dc4651cb6ed1d210 to your computer and use it in GitHub Desktop.
Hook that helps to setTimeout in react in correct way (Typescript)
import { useEffect, useMemo } from 'react'
type tTimeoutId = number
const useTimeout = () => {
const timeoutsSet = useMemo(() => new Set<tTimeoutId>(), [])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _setTimeout = (callback: any, delay?: number) => {
const timeout = setTimeout(callback, delay)
timeoutsSet.add(timeout)
return timeout
}
const _clearTimeout = (timeout?: tTimeoutId) => {
if (timeout) {
clearTimeout(timeout)
timeoutsSet.delete(timeout)
}
}
useEffect(() => {
return () => {
timeoutsSet.forEach((timeout) => {
clearTimeout(timeout)
})
timeoutsSet.clear()
}
}, [])
return { setTimeout: _setTimeout, clearTimeout: _clearTimeout }
}
export { useTimeout }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment