In this lesson, we'll create a Stopwatch
component that will store the current time in its state. We will then have the DOM display the current time as the state is updated.
We'll cover:
useState
hookinterval
using React's useRef
handleRunClick
function that handles flipping the running
state plus creating and clearing an interval
useEffect
hook to clear the interval
when the component unmountsThanks for the great overview of new stuff! If I understood correctly, using normal variable for intervalRef instead of react reference, wouldn't change anything. But then, why did you go with react ref for it?
Not quite. The fact that it "works" when you try that is actually a side-effect of the fact that it's happening so quickly. Dig a little deeper and you'll see that it doesn't actually do what you think it's doing if you don't use the ref.
I'm struggling to see the difference between useRef
and useState
in the context of this example. Are they interchangeable for keeping the interval ref?
Great to know that we can use refs to something other than DOM nodes. So many info in just 5 minutes!
Krasimir, we could actually use useState
for the intervalId, and then call the updater (setIntervalId
) instead of setting intervalId.current
. The difference is that with useState
, using the updater will trigger a re-render. In our case we don't need a re-render when the interval id is set so it's better to use useRef
.
Ah right. It makes sense. Thanks for the clarification.
It's no doubt a useful tip to use useRef
instead of a variable - thanks!
Is it something related to how the browser works with clearInterval
or rather React's hook internals specifics that it doesn't work as expected with a variable rather than a value of useRef
?
It's more just about how JavaScript works. Every time the component is rendered, that function is called again. We need to have some mechanism to keep track of that value between renders and that's what refs are intended for.
Thanks!
How about a variable outside the component function?
That would work, but what if I want to render more than one in my app?
Thanks for explaining useRef in this example.
Here is the official documentation around this usage. https://reactjs.org/docs/hooks-reference.html#useref https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
Thanks Gaurav for pointing out the detail documents about useRef. I can see some related phrases like
Looks like the code is no longer at sandbox...