Skip to content

Instantly share code, notes, and snippets.

@mohanramphp
Created January 9, 2019 08:52
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mohanramphp/af4f0267f5b1c3c0e726e18019eb2a0b to your computer and use it in GitHub Desktop.
Save mohanramphp/af4f0267f5b1c3c0e726e18019eb2a0b to your computer and use it in GitHub Desktop.
DateTime Component using React hooks
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>
);
}
@Deewens
Copy link

Deewens commented Nov 19, 2020

Thanks! It helped me to understand useEffect. I just have a question, why did you put an empty array after useEffect ?

@VaseaLuca
Copy link

@Deewens to prevent an endless loop

@purvisampat
Copy link

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.

@avijit852
Copy link

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

@akbar1155
Copy link

OOOOO zo'r ekan lekin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment