JacopoStanchi
JacopoStanchi

Reputation: 2136

What's the risk of modifying the state without setState?

I know that modifying directly the state without setState(...) won't update the UI automatically, but I can still do this:

this.state.myValue = "foo";
this.forceUpdate();

I am also aware that React waits for certain moments to update several components in a single pass, but are there really any compelling reason why I shouldn't alter directly the state without setState(...)?

There are 2 scenarios where altering directly the state would be beneficial for me:

Thank you for your help.

Upvotes: 6

Views: 169

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36564

The risks of modifying the state with out setState() are:

  • Changing the state directly will not let you have the render() method called and other life cycle methods.
  • setState() changes the DOM otherwise nothing will be changed
  • The docs says: state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props

Upvotes: 0

Anil Kumar
Anil Kumar

Reputation: 2309

If you modify state directly and at same time some other logic also updates state. It is not guaranteed that you have correct state or other logic is having correct state.

It might give you unpredictable results and behavior. So it is always advisable to use only setState() as this is async and update state immutably.

Upvotes: 1

Related Questions