Home > Software design >  React Functional Component not consistent in changing state of number as per setInterval
React Functional Component not consistent in changing state of number as per setInterval

Time:12-22

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?

CodePudding user response:

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)}
}, [])

CodePudding user response:

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)}
},[])
  • Related