0

I am reading the document of Reactjs about not mutating data. I do not understand the difference between 2 pieces of code in document's example:

handleClick() {
  // This section is bad style and causes a bug
  const words = this.state.words;
  words.push('marklar');
  this.setState({words: words});

}

and:

handleClick() {
  this.setState(prevState => ({
   words: prevState.words.concat(['marklar'])
  }));
}

Why the second code does not mutate the data?

2
  • In the first, you're pushing to the reference of the array. On the second, you copy the array with concat and does not mutate current state Commented Sep 22, 2017 at 14:39
  • concat returns a new array. Commented Sep 22, 2017 at 14:44

2 Answers 2

1

Simply put, concatreturns a new copy of the array, hence it doesn't mutate the previous array.

Sign up to request clarification or add additional context in comments.

Comments

0

In the first example you have an array and are adding a new item, by using push to this array.

In the second example you are creating a copy of the array, by using concat and adding the item, which means you do not mutate the original array. concat returns a new array.

In the second example you are not mutating the original array. Not mutating state is an important principle in React and Redux.

There is a good answer here explaining the reasons for avoiding mutation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.