I want to create timer with millisecond 3 digits. (like a stop watch)
So, I using setInterval with 1 millisecond.
For a while, (about 20sec) it was very lag. and make my computer so slowly. then I should to refresh this page 😢
I using with useEffect with setInterval. I think the problem is caused by re-render every millisecond. But I do not know how to improve performance.
Here is my code (or code-sandbox https://codesandbox.io/s/peaceful-allen-gcdorn?file=/src/userTimer.js:0-603)
// App.js
import { useState } from "react";
import useTimer from "./userTimer";
export default function App() {
const [isStart, setIsStart] = useState(false);
const [timer, setTimer] = useState("0.000");
useTimer(isStart, setTimer);
return (
<div className="App">
<div style={{ fontSize: "4rem" }}>{timer}</div>
</div>
);
}
// userTimer.js
import { useEffect, useRef } from "react";
const useTimer = (isStart, setTimer) => {
const refId = useRef();
useEffect(() => {
if (isStart) {
const startTime = Date.now();
const id = setInterval(function () {
const elapsedTime = Date.now() - startTime;
const formatTime = (elapsedTime / 1000).toFixed(3);
setTimer(formatTime);
}, 1);
refId.current = id;
}
return () => clearInterval(refId.current);
}, [isStart, setTimer]);
const stopTimer = () => clearInterval(refId.current);
return { stopTimer };
};
export default useTimer;
NOTE: I should to setTimer and setIsStart in parent component(not in useTimer) because I want to pass that hook into other child component.