DEV Community

Cover image for Build a Timer with React Hooks

Build a Timer with React Hooks

Adesile Emmanuel on August 22, 2020

In this tutorial, you will learn how to build a timer using react hooks. React hooks is the new way of building react apps and its been available s...
Collapse
 
viclafouch profile image
Victor de la Fouchardière • Edited

I think you can better optimize your code, for example by avoiding multiple re-rendering.

test

But nice tutorial ! Just don't forget performances!

Collapse
 
rad_val_ profile image
Valentin Radu

To be superfluous and point out that performance doesn't matter unless it matters (aka don't optimize before you measure and decide it's a problem based on specs and common sense), in a real world app I'd group seconds and minutes like you did, but keep the counter out and suffer the little performance penalty each second while making everything more readable and naturally fitting the model most of us have in mind when we think about time (seconds, minutes).

Collapse
 
emmaadesile profile image
Adesile Emmanuel

Yeah. I tried to avoid making hasty performance optimizations but that's definitely something to consider in a real-world app.

Collapse
 
emmaadesile profile image
Adesile Emmanuel

Thanks for the feedback.

Collapse
 
atellmer profile image
AlexPlex

Set state in React will called asynchronously one time, so that this optimization doesn't need at all.

Collapse
 
viclafouch profile image
Victor de la Fouchardière

Just console.log, you will see 3 log, because of 3 updates state ;)

Here, we will have only 1 rerender

Thread Thread
 
atellmer profile image
AlexPlex

I checked useState behavoiur and I have 1 render. See example codesandbox.io/s/sweet-star-er91q?...

Thread Thread
 
viclafouch profile image
Victor de la Fouchardière • Edited

It's because it comes from an event, like a click on a button.

React currently will batch state updates if they're triggered from within a React-based event, like a button click or input change. It will not batch updates if they're triggered outside of a React event handler, like an async call.

Thread Thread
 
atellmer profile image
AlexPlex

Yea, you're right. I didn't know it. Thanks. But what's reason for work batching only in event handlers?

Collapse
 
sunks profile image
Igor

It will not corectlly work on not active tab =(

Collapse
 
franklingarcia profile image
Franklin-Garcia

somebody knows why have a delay when start the timer and how eliminate it ??