Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • If I have to modify an element of a very long array, the performance gain from the 'cluster update' of setState(...) would be negligible compared to the performance gain from not shallow copying the entire array every time.

  • If I have 2 references to the same object in 2 different properties of the state and I want to modify this object, I would prefer to do this modification on a single property, but if I use setState(...) I would copy the object and lose the reference.

Thank you for your help.

like image 936
JacopoStanchi Avatar asked Feb 18 '19 00:02

JacopoStanchi


People also ask

Can state be changed without setState?

In other words, if we update state with plain JavaScript and not setState , it will not trigger a re-render and React will not display those (invalid) changes in state to our user. This is a simple, but crucial lesson to remember.

Why do you need to use setState () to update state in React?

Always use the setState() method to change the state object, since it will ensure that the component knows it's been updated and calls the render() method.

What happens if we modify the state manually in react JS?

So, when you mutate the state directly and call setState() with an empty object. The previous state will be polluted with your mutation. Due to which, the shallow compare and merge of two states will be disturbed or won't happen, because you'll have only one state now.

What would happen if you update the state directly?

When you directly update the state, it does not change this. state immediately. Instead, it creates a pending state transition, and accessing it after calling this method will only return the present value. You will lose control of the state across all components.


1 Answers

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.

like image 124
Anil Kumar Avatar answered Oct 25 '22 02:10

Anil Kumar