Last active
December 12, 2019 22:37
-
-
Save andycarrell/92a0f478518585c5cb18aa1244b6cb86 to your computer and use it in GitHub Desktop.
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
function useTimeout() { | |
const ids = React.useRef([]); | |
React.useEffect(() => () => ids.current.forEach(clearTimeout), []); | |
// setTimeout takes a callback and a delay, then returns the id associated with the timeout. | |
const _setTimeout = React.useCallback((callback, delay) => { | |
const id = setTimeout(callback, delay); | |
ids.current.push(id); | |
return id; | |
}, []); | |
return _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
function useSetTimeoutCleanup() { | |
const ids = React.useRef([]); | |
React.useEffect(() => () => ids.current.forEach(clearTimeout), []); | |
const withCleanup = React.callback(id => { | |
ids.current.push(id); | |
return id; | |
}, []); | |
return withCleanup; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment