Home > database >  why does all other values update while i used useEffect() on just 'time'?
why does all other values update while i used useEffect() on just 'time'?

Time:12-28

The gap variable should just give a difference once, but it gives a diff every second. I am not even updating its state. Even if i use settime in useEffect still the other variable that are changing in background are still effecting the page and are updating.

const ftime = dayjs('Dec 31,2021').unix();
const dateVar = dayjs().unix();
const gap = ftime - dateVar;

const [time, settime] = useState(dayjs().format('DD/MM/YYYY'));

useEffect(() => {
  setInterval(() => settime(dayjs().second()), 1000);
}, []);

return (
  <div className="App">
    <div>{time}</div>
    <div>{gap}</div>
  </div>
)

CodePudding user response:

useEffect(() => {
 setInterval(() => settime(dayjs().second()), 1000)
}, [])

settime is invoked for every 1000ms. This will update the state (time) and trigger a rerender.

 const ftime = dayjs('Dec 31,2021').unix();
 const dateVar = dayjs().unix();
 const gap = ftime - dateVar;

As these three variables are initialised at the top level of the function, the rerender will initialise them every time.

If you want to prevent this, you can move the variables outside the function component.

CodePudding user response:

It is updating every second because you change time every second, which the component renders.

This rerendering will also cause the constants ftime and dateVar to reinitialise every second. If this is not intended, you need to put them outside the function or wrap them in a hook, such as useState or useMemo.

You can solve the rerendering issue by making the time a React component and placing the interval effect in that component. A child's rerendering normally doesn't trigger a rerender in the parent.

  • Related