Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

321
Views
How can I improve performance setInterval per millisecond using by hooks in React?

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!