Created
December 11, 2020 08:25
-
-
Save mlshv/1421b6ace6156edef9b84bf2b33746ef to your computer and use it in GitHub Desktop.
useTimeout
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
import { useState, useEffect } from 'react' | |
const removeKeyFromState = (key, setState) => { | |
setState(({ [key]: deletedKey, ...restKeys }) => ({ ...restKeys })) | |
} | |
const useTimeout = () => { | |
const [timeouts, setTimeouts] = useState({}) | |
useEffect(() => { | |
return () => Object.values(timeouts).forEach(window.clearTimeout) | |
}, []) | |
const createTimeout = (callback, time, id = Math.random().toString()) => { | |
if (timeouts[id]) { | |
window.clearTimeout(timeouts[id]) | |
} | |
const timeout = window.setTimeout(() => { | |
callback() | |
removeKeyFromState(id, setTimeouts) | |
}, time) | |
setTimeouts((oldTimeouts) => ({ ...oldTimeouts, [id]: timeout })) | |
} | |
const cancelTimeout = (id) => { | |
window.clearTimeout(timeouts[id]) | |
removeKeyFromState(id, setTimeouts) | |
} | |
return { createTimeout, cancelTimeout } | |
} | |
export default useTimeout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment