Created
December 27, 2019 11:58
-
-
Save resir014/6de144716a6f4de0e0767996ffccb69c to your computer and use it in GitHub Desktop.
useClock hook
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 * as React from 'react' | |
import useInterval from './useInterval' | |
export default function useClock() { | |
const [time, setTime] = React.useState<Date>(new Date()) | |
const tick = () => { | |
setTime(new Date()) | |
} | |
useInterval(tick, 500) | |
return time | |
} |
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 * as React from 'react' | |
/** | |
* `useInterval()` hook stolen from Dan's blog: | |
* https://overreacted.io/making-setinterval-declarative-with-react-hooks/ | |
*/ | |
export default function useInterval(callback: () => void, delay: number = 1000) { | |
const savedCallback = React.useRef<any>() | |
// Remember the latest callback. | |
React.useEffect(() => { | |
savedCallback.current = callback | |
}, [callback]) | |
// Set up the interval. | |
React.useEffect(() => { | |
function tick() { | |
savedCallback.current() | |
} | |
const id = setInterval(tick, delay) | |
return () => clearInterval(id) | |
}, [delay]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment