Skip to content

Instantly share code, notes, and snippets.

@resir014
Created December 27, 2019 11:58
Show Gist options
  • Save resir014/6de144716a6f4de0e0767996ffccb69c to your computer and use it in GitHub Desktop.
Save resir014/6de144716a6f4de0e0767996ffccb69c to your computer and use it in GitHub Desktop.
useClock hook
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
}
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