Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

327
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda