patternjavascriptreactCritical
Correct modification of state arrays in React.js
Viewed 0 times
correctreactmodificationstatearrays
Problem
I want to add an element to the end of a
I'm concerned that modifying the array in-place with
The alternative of making a copy of the array, and
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.Solution
The React docs says:
Treat this.state as if it were immutable.
Your
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
The memory "waste" is not an issue compared to the errors you might face using non-standard state modifications.
Alternative syntax for earlier React versions
You can use
In ES6 you can use the Spread Operator:
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. For example, it could lead to that some lifecycle methods like componentDidUpdate won’t trigger.The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
this.setState(prevState => ({
arrayvar: [...prevState.arrayvar, newelement]
}))The memory "waste" is not an issue compared to the errors you might face using non-standard state modifications.
Alternative syntax for earlier React versions
You can use
concat to get a clean syntax since it returns a new array:this.setState({
arrayvar: this.state.arrayvar.concat([newelement])
})In ES6 you can use the Spread Operator:
this.setState({
arrayvar: [...this.state.arrayvar, newelement]
})Code Snippets
this.setState(prevState => ({
arrayvar: [...prevState.arrayvar, newelement]
}))this.setState({
arrayvar: this.state.arrayvar.concat([newelement])
})this.setState({
arrayvar: [...this.state.arrayvar, newelement]
})Context
Stack Overflow Q#26253351, score: 992
Revisions (0)
No revisions yet.