DEV Community

Almuhannad_01
Almuhannad_01

Posted on

How can I build a time that changes every second on React.js?!

--> The technicals which will use in this program (React.js, React Hooks - useState).


The program..
1) add:

import React, {useState} from "react";

2) add function which name the same for the file e.g// App

function App() {

setInterval(sayHi, 1000) --> This function prints sayHi every second, but you will add setInterval(updatetime, 1000);

const now = new Date(); --> This is the object for the Date. For example// you can get the hour when you write const now = new Date ().getHours();, but here you want full-time (( hour: min: sec AM/PM )) for that, will use:
const now = new Date().toLocaleTimeString();

3) add hooks:



const [time,setTime] = useState(now);


Enter fullscreen mode Exit fullscreen mode

4) update function time:



function updatetime() {
    const newtime = new Date().toLocaleTimeString();
    setTime(newtime);
  }


Enter fullscreen mode Exit fullscreen mode

5) Program output to the user:



return(
    <div>
      <h1>{time}</h1>
    </div>
);


Enter fullscreen mode Exit fullscreen mode

Final file will be 🎈:

Image description

Image description

😍
Thank you..

Top comments (4)

Collapse
 
fjones profile image
FJones

Raw use of setInterval in React causes quite a few problems. Not least of all that this will cause a litany of console messages if used in any nested component that gets unloaded or rerendered (In fact, without verifying it, I would suspect that this particular implementation would very quickly flood the JS engine with timers, since App gets rerendered for every execution of the interval function).

Collapse
 
clay profile image
Clay Ferguson

Yes, he should be creating only one 'setInterval' or else doing a clearInterval, before creating a new one (that's definitely a bug), but I don't understand why you say setInterval is dangerous in React. Is there a better way to do a repeating timer in React?

Collapse
 
fjones profile image
FJones

Well, the canonical way would be Dan Abramov's useInterval hook, which also illustrates some other issues of raw setInterval.

And what I mean is that, with every rerender of App, we call setInterval. Because the function passed to setInterval contains a call to setTime, on every timer tick, a rerender is queued. On that rerender, a new timer is created, itself calling setTime, and so on. Now, React batches the rerenders so it doesn't explode completely, and you might only notice some slowdown on the client (since the use of the Date object at least minimizes timer drift), but under the hood that tab probably doesn't have too much fun managing that event loop after a few minutes.

Thread Thread
 
clay profile image
Clay Ferguson • Edited

I read that Abramov link, and my conclusion is there's nothing wrong with using setInterval in a react app if you know what you're doing. It works and works as expected. It executes code upon regular intervals.

The mistake people make is to consider it part of the GUI when it should be part of the Data Model/State. If someone is using Redux for example, you can have a setInterval that updates state at regular intervals, and the RIGHT way to do that is indeed with setInterval, and it will work perfectly in React, with no special coding or workarounds like Abramov has done.

The fact that render methods get called at essentially non-predictable times as React deems necessary is just something people need to be aware of, because there's all kinds of bugs that can happen if you aren't aware of it. setInterval is just one of the million things you could do wrong by misunderstanding the fact that render methods are called sort of 'at random', so to speak.