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

157
Visualizações
React useEffect empty dependency

The problem: when I remove the dependency array in useEffect the timer never stops. But when I add a dependency array in useEffect the timer gets stuck on 5.

How can I solve this?

const App = () => {
  const [inputValue, setInputValue] = useState("");
  const [target, setTarget] = useState([]);
  const [score, setScore] = useState(0);
  const [timer, setTimer] = useState(5);

  const newQuestion = () => {
    const minimum = 1;
    const maximum = 10;
    const int1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
    const int2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
    setTarget([int1, int2]);
  };

  const handleReset = () => {
    setScore(0);
    setTimer(5);
  };

  useEffect(() => {
    newQuestion();
  }, [score]);

  useEffect(() => {
    let interval = setInterval(() => {
      setTimer((prev) => {
        if (prev === 1) clearInterval(interval);
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(interval);
  });

  const handleAnsewer = () => {
    const total = target[0] + target[1];

    if (total === Number(inputValue)) {
      setScore(score + 1);
    } else {
      if (score > 0) {
        setScore(score - 1);
      }
    }

    setInputValue("");

    newQuestion();
  };

  return (
    <>
      <h1>Random Math Quiz</h1>

      <h1> {target.join(" + ")} </h1>

      <h1> Timer: {timer} </h1>

      <input placeholder="Answer" value={inputValue} onChange={(e) => setInputValue(e.target.value)} />

      <div>
        <button disabled={timer === 0} onClick={handleAnsewer}>
          {" "}
          Submit{" "}
        </button>
      </div>

      <div>
        <button onClick={handleReset}> play again </button>
      </div>

      {score === 10 && <h1> (Score: 10 / {score}) Congrate you are master in Math!</h1>}
      {score <= 9 && timer < 1 && <h1> ( Score: 10 / {score}) Oh boy this is the math class!</h1>}
    </>
  );
};

export default App;
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Change your useEffect containing the setInterval method with this one:

useEffect(() => {
  if (timer > 0){ 
    setTimeout(() => {setTimer(timer - 1)}, 1000)
  }
}, [timer])

I think the approach with setTimeout() is better because you don't need to clear intervals or any of that nonsense.

How it works

  1. Is the condition met?
  2. If yes, update setTimer to new time timer - 1 after 1000ms
  3. timer changes and so it will trigger useEffect and the component will re-render
  4. This will go on until the timer doesn't change. When it hits 0
about 4 years ago · Santiago Trujillo 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