Following comes from React tutorial:
const squares = this.state.squares.slice();
squares[i] = 'X';
this.setState({squares: squares});
This code changes copied state.squares and assign it to orginal state.squares. Finally this changes original state.squares, so I think this is not different than mutable code like following:
this.state.squares[i] = 'X';
Is there some difference?
This code is immutable, because
slice()method is used. If you try:You'll get new array created by
slice()method.You can test it that way:
And if you have doubts about
this.setState({squares: squares});- yes, of course after running this you have new state, but in fact this state is not modified old state object, but new object created from old parts. So if you try:You'll see that new state will differ than saved old:
In case of
this.state.squares[i] = 'X';oldStatewould be modified too and that is exactly what we call mutability. All copied parts of old state changes with it and that causes many problems.