chrisdew chrisdew - 1 year ago 117
Javascript Question

Correct modification of state arrays in ReactJS

I want to add an element to the end of a

array, is this the correct way to do it?


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

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

Answer Source

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()
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:

    arrayvar: this.state.arrayvar.concat([newelement])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download