HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

Correct way to push into state array

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
waycorrectintostatepusharray

Problem

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] );

Code Snippets

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

Context

Stack Overflow Q#37435334, score: 246

Revisions (0)

No revisions yet.