Skip to content

Instantly share code, notes, and snippets.

@srph
Last active June 2, 2019 12:30
Show Gist options
  • Select an option

  • Save srph/a6796ddd842bd6b3aa807a877f11ac0b to your computer and use it in GitHub Desktop.

Select an option

Save srph/a6796ddd842bd6b3aa807a877f11ac0b to your computer and use it in GitHub Desktop.
React Hook: Get an updated current date instance every second

Usage

import { useNow } from './useNow'

function MyApp() {
  const now = useNow({ interval: 1000 })
  
  return (
    <div>The current date is {now}</div>
  )
}
import { useState } from 'react'
import useInterval from '@use-it/interval'
interface Props {
interval: number
}
/**
* Provides you an updated current date instance
*/
function useNow(props: Props) {
const [now, setNow] = useState(() => new Date())
useInterval(() => {
setNow(new Date())
}, props.interval)
return now
}
export {
useNow,
useNow as default
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment