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

185
Visualizações
How to use setInterval with react useEffect hook correctly?

I tried to create a simple timer app with ReactJS and found the below code on the internet.

Does the function that we passed to the useEffect will execute with the dependency change or does it recreates with every dependency change and then execute?

Also I console log the return function of the useEffect and it runs with every render. Does it run only when the component unmount? or with every render?

import { useEffect,  useState } from "react";

const App = () => {
  const [isActive, setIsActive] = React.useState(false);
  const [isPaused, setIsPaused] = React.useState(true);
  const [time, setTime] = React.useState(0);

  React.useEffect(() => {
    let interval = null;

    if (isActive && isPaused === false) {
      interval = setInterval(() => {
        setTime((time) => time + 10);
      }, 10);
    } else {
      clearInterval(interval);
    }
    return () => {
      console.log("cleanup");
      clearInterval(interval);
    };
  }, [isActive, isPaused]);

  const handleStart = () => {
    setIsActive(true);
    setIsPaused(false);
  };

  const handlePauseResume = () => {
    setIsPaused(!isPaused);
  };

  const handleReset = () => {
    setIsActive(false);
    setTime(0);
  };

  return (
    <div className="stop-watch">
      {time}
      <button onClick={handleStart}>start</button>
      <button onClick={handlePauseResume}>pause</button>
      <button onClick={handleReset}>clear</button>
    </div>
  );
};

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The code inside the useEffect hook will run every time a dependency value has been changed. In your case whenever isActive or isPaused changes state.

This means that the reference to the interval will be lost, as the interval variable is redefined.

To keep a steady reference, use the useRef hook to have the reference persist throughout state changes.

const App = () => {
  const [isActive, setIsActive] = useState(false);
  const [isPaused, setIsPaused] = useState(true);
  const [time, setTime] = useState(0);
  const interval = useRef(null)

  useEffect(() => {
    if (isActive && !isPaused) {
      interval.current = setInterval(() => {
        setTime((time) => time + 10);
      }, 10);
    } else {
      clearInterval(interval.current);
      interval.current = null;
    }

    return () => {
      clearInterval(interval.current);
    };
  }, [isActive, isPaused])

  ...
}
about 4 years ago · Juan Pablo Isaza Relatório
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