Home > Software design >  If I use array.shift() on this.state.array, should I use setState after?
If I use array.shift() on this.state.array, should I use setState after?

Time:01-12

If I run

this.state={
    myArray: [1,2,3,4]
}

let element = this.state.myArray.shift()

then this.state.myArray will be [2,3,4].

I understand the recommendation is to use setState to avoid race conditions, but since shift() has already done the shifting, it seems unecessary to use setState afterwards.

Is this OK or is there a recommended way to deal with shifting?

CodePudding user response:

It is necessary.

This code is buggy by definition, as you have mutated the state without going through setState -- which is explicitly not allowed in react. That means a re-render will not be triggered, and so anything in render that uses this piece of state will not recalculate, and the DOM displayed to the user will not change.

Use:

this.setState(prev => ({ myArray: prev.myArray.slice(1) }))

Note slice does not modify this.state.myArray directly like shift does, it returns a new copy with the first item removed.

  • Related