Created
January 9, 2019 08:52
-
-
Save mohanramphp/af4f0267f5b1c3c0e726e18019eb2a0b to your computer and use it in GitHub Desktop.
DateTime Component using React hooks
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 React, { useState, useEffect } from 'react'; | |
export const DateTime = () => { | |
const [dateTime, setDateTime] = useState(new Date()); | |
useEffect(() => { | |
const id = setInterval(() => setDateTime(new Date()), 1000); | |
return () => { | |
clearInterval(id); | |
} | |
}, []); | |
return ( | |
<h4>{`${dateTime.toLocaleDateString()} ${dateTime.toLocaleTimeString()}`}</h4> | |
); | |
} |
Thanks! It helped me to understand useEffect. I just have a question, why did you put an empty array after useEffect ?
The empty array is basically a list of dependencies. The list contains the states the change depends up on.
sometimes when i use new Date() on react it's not working but when in use only Date() it's work but Date related other function it's not working just like dateTime.toLocaleTimeString() it's not working. i don't understand what is the problem plz help if you know
OOOOO zo'r ekan lekin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Deewens to prevent an endless loop