DEV Community

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

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.