Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is React's setState() guaranteed to create a new state object every time?

In React, does setState always assign a new object to this.state? In other words, when you call:

this.setState({
  key1: val1,
  key2: val2
});

does it always merge the current state object with the new properties into a new object, queueing an operation which is functionally equivalent to the following?

this.state = {
   ...this.state,
   key1: val1,
   key2: val2
};

The reason I'm asking is that I'd like to know whether this.state !== nextState is always guaranteed to be true inside shouldComponentUpdate() if the update was triggered by setState.

Thanks.

like image 514
philraj Avatar asked Aug 13 '17 02:08

philraj


People also ask

What does setState () do and how does it work?

It ensures that the component has been updated and calls for re-rendering of the component. setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value of object after update using setState it may not get give current updated value on console.

Does setState always re-render?

setState() will always lead to a re-render unless shouldComponentUpdate() returns false . To avoid unnecessary renders, calling setState() only when the new state differs from the previous state makes sense and can avoid calling setState() in an infinite loop within certain lifecycle methods like componentDidUpdate .

Is setState a promise?

setState uses callbacks and doesn't return a promise. Since this is rarely needed, creating a promise that is not used would result in overhead. In order to return a promise, setState can be promisified, as suggested in this answer.

Can you use setState twice?

If you have ever tried to set a state variable multiple times in a row in a React component, you may have been surprised to find that it didn't quite work. It would be reasonable to expect that, every time you click the “Increment Twice” button, count will increase by two.


2 Answers

The simple answer to your question will be "Yes", but for one update cycle. Let me explain this.

As you may already know React setState does not always immediately update the component. Sometimes React batch or defer the updates until later. As an example, let's assume you have something like follows in your event handler.

onClick() {
  this.setState({quantity: state.quantity + 1});
  this.setState({quantity: state.quantity + 1});
  this.setState({quantity: state.quantity + 1});
}

These state update will be queued and execute all together in one update cycle. In such scenario React only create a new state object for the first setState and that object will mutate for subsequent setState updates. You can clearly see this in the source code here.

However, this is something totally about how React works under the hood and we won't need to worry about that. Because there will be only one shouldComponentUpdate() and componentDidUpdate() for one cycle. By the time we access the state it will be always a new object. So we can safely assume that setState() guaranteed to create a new state object every time. But make sure that you aware of other implications of setState which explains in the official documentation.

I'd like to know whether this.state !== nextState is always guaranteed to be true inside shouldComponentUpdate().

The answer to your this question will be "No" as also explained in other answers. shouldComponentUpdate() will be called because of either state change, props change or both. So this.state !== nextState won't true if the component has updated only because of props change.

like image 84
Tharaka Wijebandara Avatar answered Oct 10 '22 01:10

Tharaka Wijebandara


I think you want to know the answer to this question.

Will this.state !== nextState is always guaranteed to be true inside shouldComponentUpdate() ?

According to react docs shouldComponentUpdate will be called on three instance

  • state changed
  • props changed
  • state and props changed

So if only props are changing, your current state will be equal the last unmodified state.

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

The first question that you asked are depends on your style of data management for your state.

React lets you use whatever style of data management you want, including mutation.

And the docs also states that

shallow merge of stateChange into the new state, e.g., to adjust a shopping cart item quantity

But looking at the internal parts of setState beginUpdateQueue method let me doubtful when state gets mutated.

I think it would be wise to use immutability-helper for this part of the code, if you must guarantee that no mutation happens to the data.

like image 31
eenagy Avatar answered Oct 10 '22 00:10

eenagy