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 setState
ing that seems wasteful.
Use setState() Method in React React components internally use the setState() method to modify the state. It is a strong recommendation from React team to only mutate the state using the setState() method and not bypass it. It takes one argument: an object that's supposed to take the place of the existing state.
The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component.
To update state , React developers use a special method called setState that is inherited from the base Component class. The setState method can take either an object or a function as the first argument.
Arrays in React State export default App; As mentioned, the initial array state is done in the React component's constructor and afterward used within the render() method to display it. Every time the state changes, the render method will run again and display the correct state in your browser.
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. F.ex, 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] })
Easiest, if you are using ES6
.
initialArray = [1, 2, 3]; newArray = [ ...initialArray, 4 ]; // --> [1,2,3,4]
New array will be [1,2,3,4]
to update your state in React
this.setState({ arrayvar:[...this.state.arrayvar, newelement] });
Learn more about array destructuring
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With