'What is the difference of useRef and Variable when useEffect is used once?
I wanted to make a simple timer using useEffect in react. As I don't want to make an infinite loop, I didn't give a dependencies, leave it with an empty array. However, it was not reflected in UI.
1.Then What is the reason should I use useRef?
2. Why variable in useEffect is recreated after useEffect is called(using dependencies)?
3. What is the difference between variable and useRef in this case(not using dependencies, using []) as variable and useRef both changes and not reflected in UI?
import React,{useState,useEffect,useRef} from 'react';
function Timer(){
let timer=useRef(0);
useEffect(() => {
let timer=setInterval(()=>{timer.current+=1;
console.log(timer.current)},1000);
return () => {
clearInterval(timer);
};
}, []);
return(
<div>
{timer.current}
</div>
)
}
export default Timer;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
