Andy
Andy

Reputation: 1630

Why to avoid this.setState(this.state)?

In React, I tried both:

they both work and both produce the same results. Why is it suggested (in the docs) to set to the state clone (with Object.assign) instead of setting to the state itself? Does the object identity of the state matters in React(without Redux)? It seems like as long as you call setState, the render() will get triggered anyway regardless of the state object identity.

Upvotes: 2

Views: 1827

Answers (2)

Aanchal1103
Aanchal1103

Reputation: 915

Javascript objects and arrays are passed through reference and not value, when we say

stateClone = this.state

we’re not making a copy of the state object,  we are just creating a new reference to the same object (this.state). Now, if we make any changes to stateClone like

stateClone.someProp = someValue

we actually mutate the original state directly, which is prohibited since mutations made this way might be overridden on the next setState call.

That is why, Object.assign or spread operator (...) is used to create a copy of the state object and changes are made to that copy.

More info: https://medium.com/pro-react/a-brief-talk-about-immutability-and-react-s-helpers-70919ab8ae7c

Upvotes: 4

Andy
Andy

Reputation: 1630

setState doesn't care if the object you set has the same reference as the current state. render() will be called either way.

Immutability is useful only for shallow checking (using === to compare before and after) in the context of optimization with the shouldComponentUpdate lifecycle method, which by default returns true.

Upvotes: 1

Related Questions