setInterval in state

(Thord Lindé) #1


I’ve created a simple counter and initiate setInterval like this, to be able to clearInterval.

this.setState({interval: setInterval( this.increaseCount, this.state.speed )})

It works perfect - but is it best practice to put interval in state?

All code here:

(Ulrik Walter) #2

I think:

this.interval = setInterval(this.increaseCount, this.state.speed)

Use setState() to re-rendering. (If a variable is in the DOM)

(Jakob Lind) #3

There is a similar example on in section “A Stateful Component”. They don’t put interval in state. But they put it in a local variable, like this:

this.interval = setInterval(() => this.tick(), 1000);

Why? The reference to interval is static, you don’t expect it to change a lot. State is for data that you want to change in a predictable maner.

(Thord Lindé) #4

It was some time ago I wrote this question so I have already rewritten the app, in a similar way you are suggesting.

Thank you all the same!