setInterval in state


(Thord Lindé) #1

Hi

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

componentDidMount(){
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: https://codepen.io/Thord/pen/eEeMrw


(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 https://reactjs.org/ 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!