1

I want to know the reason that we use only setState() to update states in React?

Why can't we do this one?

this.state.vote = this.state.vote + 1
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84
  • 3
    You can read the [State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html) section of the documentation. – Tholle Jul 19 '18 at 15:26
  • check this also: https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really – Mayank Shukla Jul 19 '18 at 16:05

1 Answers1

6

The reason you need to use the setState() method is because of a concept called mutability.

When state changes in a react component, you generally want this to trigger a re-render of the component (to reflect these changes). Using setState will always trigger a re-render unless shouldComponentUpdate prevents this. By setting the property on the state object like so this.state.vote = this.state.vote + 1, you are altering the existing state object. Due to the way objects in javascript work, React can't easily tell that this object has changed.

When you use React's setState() method, you are creating a new version of the state object which React recognises and in turn knows it needs to re-render the component.

That's a simplified explanation but hopefully it explains the core concept to you.

Here's an interesting article to read about mutation

Sean
  • 2,609
  • 1
  • 18
  • 34
  • to add to this question: it not only adds a new version of the object, React creates a new tree containing the reactive elements in the component (along with the updated state). This tree is used to figure out how the component’s UI should change in response to the state change by comparing it with the elements of the previous tree. React knows which changes to implement and will only update the parts of the DOM where necessary. – Overmachine Jul 19 '18 at 15:35