import { useNow } from './useNow'
function MyApp() {
const now = useNow({ interval: 1000 })
return (
<div>The current date is {now}</div>
)
}
Last active
June 2, 2019 12:30
-
-
Save srph/a6796ddd842bd6b3aa807a877f11ac0b to your computer and use it in GitHub Desktop.
React Hook: Get an updated current date instance every second
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 } 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