I am trying to understand the useRef
hook in React.
I have created a simple countdown timer in React. The code is below.
import { useRef, useState, useEffect } from 'react';
function Parent() {
const [count,setCount]=useState(5);
const ref=useRef(0);
//let hold=0;
const countdown=()=>{
ref.current=setInterval(()=>{
// console.log('ref.current-->',ref.current);
setCount((c)=>c-1)
},1000)
}
useEffect(()=>{
if(count<1)
clearInterval(ref.current)
},[count])
return(
<>
<h3>Timer : {count}</h3>
<br/>
<button onClick={countdown}>countdown</button>
</>
)
}
export default Parent;
Here, I have created a ref using the hook and I am monitoring the count state. When it hits 0, I am calling the clearInteval
function to clear up the timer.
This code is working fine.
But when I try to do the same using a normal variable rather than the one created by the hook, the interval is not getting cleared.
Here's the modified code.
import { useRef, useState, useEffect } from 'react';
function Parent() {
const [count,setCount]=useState(5);
const ref=useRef(0);
let hold=0;
const countdown=()=>{
hold=setInterval(()=>{
// console.log('ref.current-->',ref.current);
setCount((c)=>c-1)
},1000)
}
useEffect(()=>{
if(count<1)
clearInterval(hold)
},[count])
return(
<>
<h3>Timer : {count}</h3>
<br/>
<button onClick={countdown}>countdown</button>
</>
)
}
export default Parent;
What am I not understanding here?
This code should have worked in normal JavaScript.
const myRef = useRef()
will provide a ref object such that myRef.current
's value will persist across renders. When you use let myVar = something
, myVar
will be re-created on each render, so you will lose and replace its value each time.
Your Parent
component is getting re-rendered each time your state changes, so you benefit from keeping your interval reference as a ref from useRef
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With