Last active
September 18, 2021 12:02
-
-
Save andreydro/aca2f37287506ba7dc4651cb6ed1d210 to your computer and use it in GitHub Desktop.
Hook that helps to setTimeout in react in correct way (Typescript)
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 { 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