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

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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