Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!