I was trying to see how many times the code re-render and hence used a reference Hook to check it. Though the reference variable was updating when I was using shorthand operator it was not working using assignment operator and is printing NaN.
import { useState, useRef } from 'react';
export default function Stopwatch() {
const [startTime, setStartTime] = useState(null);
const [now, setNow] = useState(null);
const ref = useRef(0);
//ref.current=ref.current+1;
ref.current+=1;
function handleStart() {
// Start counting.
setStartTime(Date.now());
setNow(Date.now());
setInterval(() => {
// Update the current time every 10ms.
setNow(Date.now());
}, 10);
}
let secondsPassed = 0;
if (startTime != null && now != null) {
secondsPassed = (now - startTime) / 1000;
}
return (
<>
<h1>Time passed: {secondsPassed.toFixed(3)}</h1>
<button onClick={handleStart}>
Start
</button>
<p>{ref.current}</p>
</>
);
}
Anything I am missing while assigning this?