Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

323
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda