1

I've read that it is not advisable to update state directly, e.g:

this.state.array = ['element'];

But, for example, consider this state:

this.state = {
    array: [],
}

updateArray = element => {
    temp = this.state.array;
    temp.push(element);
    this.setState({array: temp});
}

Isn't this essentialy the same as the first example? We are setting temp to point to this.state.array, thus mutating it and then overwriting it with this.setState().

I've seen this example in various tutorials, Wouldn't it be 'better' to make a copy of the array?

fishamit
  • 257
  • 2
  • 10
  • 1
    Possible duplicate of: https://stackoverflow.com/questions/35867038/what-the-difference-of-this-state-and-this-setstate-in-reactjs Also: https://reactjs.org/docs/state-and-lifecycle.html – devserkan Jun 18 '18 at 15:55
  • In the first example, I guess it won't change the state, and won't trigger re render – Priyesh Kumar Jun 18 '18 at 15:55
  • You are correct, this is not the recommended method, instead clone the array so that you can work on the cloned array immutably, for instance `temp = [...this.state.array];` – delinear Jun 18 '18 at 15:58
  • 1
    If the question is about immutability then: `this.setState({ array: [ ...this.state.array, element ] })` is probably the easiest, modern way of doing this. – devserkan Jun 18 '18 at 16:06
  • Or even better: `this.setState( prevState => ( { array: [ ...prevState.array, element ] } ))` – devserkan Jun 18 '18 at 16:07

2 Answers2

2

Yes, you are right it's the same thing. You should read more about pass by value and pass by reference in JS.

When we say

let x = some.array

We are copying a reference(remember copy and paste as shortcut)? Both the things actually point to the same real thing and takes no extra space.

You should instead use some JS that can do this for you.

let x = some.array.slice()

This creates real copy of the array. On modern ES2015 you can do

let x = [...some.array]

a more elegent way.

aks
  • 8,796
  • 11
  • 50
  • 78
2

Check out the docs here, https://reactjs.org/docs/state-and-lifecycle.html.

According to the React team. Setting the state directly will not re-render a component. You must use setState.

As far as using a temp variable when setting state, that is used when something needs to be done to 'element' before setting the state variable. As setState can be called asynchronously. It is acceptable in your case to just do

updateArray = (element) => {
  this.setState({ array: [ ...this.state.array, element ] });
}
Matthew Zielke
  • 151
  • 1
  • 1
  • 7