eugene
eugene

Reputation: 41665

React, reason for avoiding mutating state

I know mutating state can work against PureComponent (or similar) Is there other reason not to mutate state?

I wonder if the 3rd way is ok to do?

  // The Right Way:
  // copy the existing items and add a new one
  addItemImmutably = () => {
    this.setState({
      items: [...this.state.items, this.makeItem()]
    });
  };

  // The Wrong Way:
  // mutate items and set it back
  addItemMutably = () => {
    this.state.items.push(this.makeItem());
    this.setState({ items: this.state.items });
  };
 // is this ok? (mutate but set state with new copy)
 addItem3rdWay = () => {
   this.state.items.push(this.makeItem());
   this.setState({items: [...this.state.items]});
 }

Upvotes: 1

Views: 57

Answers (2)

Georgi Moskov
Georgi Moskov

Reputation: 36

Here is an example: You have fired an async method that sends a request with your current state data. In meantime you have executed a function that mutates the state. This will cause the async function to send the mutated state despite the fact it intended to send the state before mutation.

Upvotes: 1

Joseph
Joseph

Reputation: 4685

You can think state as your database.

You don't directly mutate your database, you modify your database by API.

setState is the API.

Of course, you can directly mutate your database, but other components will have a hard time retrieving those data, because those are inconsistent right now, because somebody doesn't use the API that framework provides for you.

If you really like the way mutating state, you can use Vue, Vue is designed like that.

Upvotes: 1

Related Questions