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

191
Visualizações
React Functional Component not consistent in changing state of number as per setInterval

Rando2.js

import React, { useState } from 'react';

const Rando2 = (props) => {
  const [num, setNum] = useState(0);

  const changeNum = () => {
    setInterval(()=>{
      let newNum = Math.floor(Math.random()*props.maxNum);
      setNum(newNum);
    }, 1000)
  }

  changeNum();

  return (
    <h1>{num}</h1>
  )
}

export default Rando2;

In the above code, there is no-error, props {maxNum: 15} is provided by parent, so that is fine. The issue is, I expect number to be changed once-every-second, it does in beginning, but as time passes --- the frequency of Number change is drastically increased, like 10 times a second then, 20 times or 30 times ... about that.

Now, is there any problem in code, why the change in number is not consistant always ...like once per second, as per the code?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The problem is because every time num state changes, you're setting a new timeout or interval. So, each time this component runs or rerenders, you have an additional interval, that's setting the new num at a different cadence, along with the original interval. Instead, you just need to set the timeout when the component loads the first time.

useEffect(() => {
 val interval = setInterval(...code...)

 return () => {clearInterval(interval)}
}, [])
about 4 years ago · Santiago Trujillo Relatório

0

In the above code, a new setInterval is scheduled after every render after sometimes multiple intervals are executed at once

Schedule setInterval at the initial render using Effect Hook so that it will execute the interval after every second

useEffect(()=>{
  setInterval(()=>{
    let newNum = Math.floor(Math.random()*props.maxNum);
      setNum(newNum);
  }, 1000)
  return () => {clearInterval(interval)}
},[])
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