DEV Community

Cover image for How to develop a Stopwatch in React JS with custom hook

How to develop a Stopwatch in React JS with custom hook

Abdul Basit on July 19, 2020

In order to truly understand how things work we should break down the task into smaller pieces, this is what we are doing here. Our ultimate goal i...
Collapse
 
jamiyand profile image
JamiyanD

tnk u it is easily understand

Collapse
 
killcodex profile image
Aaquib Ahmed

thanks, bro you saved me !! I read a lot of articles but it was very simple and easy !!

Collapse
 
killcodex profile image
Aaquib Ahmed

Bro can you write another article on ref method?

Collapse
 
abdulbasit313 profile image
Abdul Basit

Sure. What do you want to achieve with ref?

Thread Thread
 
killcodex profile image
Aaquib Ahmed

I want to understand the actual use of ref and why it should not use frequently

Thread Thread
 
abdulbasit313 profile image
Abdul Basit

in react we use useRef to get the dom element. Let say you want to find out scroll position and things like this.

Collapse
 
gayatrea profile image
gautam pal

Easy to understand

Collapse
 
shahmir049 profile image
Shahmir Faisal

Wow. Great article. Nice explanation.

Collapse
 
abdulbasit313 profile image
Abdul Basit

Thanks Shahmir... It means to me.

Collapse
 
sunflower profile image
sunflowerseed • Edited

although, is it using setInterval(fn, 1000) to count as 1 second? What if it is 1.016 seconds because JavaScript can delay and not invoke the handler until 1.016 seconds later? Then after a while, it can be off... try it with your iPhone's stopwatch and see if after 30 minutes or an hour, whether your clock is off by a few seconds.

Also if you start the time and go off exercise, come back and the computer is in a sleep, then you wake up the computer and if the processor wasn't running, your timer will be totally off?

Collapse
 
keomalima profile image
Keoma Lima

Hello! I've adapted your code on my react native application but as soon as my screen is blocked, the timer stops running, do you have any idea on how I can keep the timer running even with the screen blocked? Thanks a lot

Collapse
 
abdulbasit313 profile image
Abdul Basit

Though I haven't implemented it, but there are some events in react native that can be called on blocking the screen or going back, so on that event, you can save the timer in async storage. There can be multiple ways to achieve it...

Collapse
 
satish_kumar profile image
satish kumar

Thank you so much its a good example, ease and clean.

Collapse
 
zeealik profile image
Zeeshan Ali Khan

It helped me a lot, was making check-in/out screen in my app and it really helped me out in this.

Collapse
 
abdulbasit313 profile image
Abdul Basit

I am glad to know.

Collapse
 
miguelhv profile image
Miguel

Nice explanation, I hadn't used custom hooks previously!