javascriptreactjsimmutability

Correct way to push into state array


I seem to be having issues pushing data into a state array. I am trying to achieve it this way:

this.setState({ myArray: this.state.myArray.push('new value') })

But I believe this is incorrect way and causes issues with mutability?


Solution

  • Functional Components & React Hooks

    const [array,setArray] = useState([]);
    

    Push value at the end:

    setArray(oldArray => [...oldArray,newValue] );
    

    Push value at the start:

    setArray(oldArray => [newValue,...oldArray] );