chrisdew chrisdew - 5 months ago 27
Javascript Question

Correct modification of state arrays in ReactJS

I want to add an element to the end of a

state
array, is this the correct way to do it?

this.state.arrayvar.push(newelement);
this.setState({arrayvar:this.state.arrayvar});


I am concerned that modifying the array in-place with
push
might cause trouble - is it safe?

The alternative of making a copy of the array, and
setState
ing that seems wasteful.

Answer

The React docs says:

Treat this.state as if it were immutable.

Your push will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards.

A better option would be as you mentioned:

var arrayvar = this.state.arrayvar.slice()
arrayvar.push(newelement)
this.setState({ arrayvar: arrayvar })

The "waste" here is minimal compared to potential race conditions. You can also use concat to get a cleaner syntax since it returns a new array:

this.setState({ 
    arrayvar: this.state.arrayvar.concat([newelement])
})