Correct modification of state arrays in React.js
Asked 07 September, 2021
Viewed 610 times
  • 52
Votes

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'm 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 setStateing that seems wasteful.

16 Answer