Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand way to setState() in React?

Tags:

reactjs

jsx

Lets say I initialize the state of a component like so:

getInitialState: function(){
   return {name: "Bob Smith",
           phone: "555-555-5555",
           location: "San Francisco, CA",
           best-friend: "Bill Jacobson",
           favorite-color: "Orange"}
},

Then if I just want to modify one of those states I was told that the following was a no-no:

this.state.name = "John Smith";

But rather I should use:

this.setState({name: "John Smith",
               phone: this.state.phone,
               location: this.state.location,
               best-friend: this.state.best-friend,
               favorite-color: this.state.favorite-color});

There must be a more efficient way to do this. Is there a shorthand way to change just one property of my state object in a way that is safe for react?

like image 783
FactorialTime Avatar asked Dec 24 '22 04:12

FactorialTime


1 Answers

Actually, you do not have to specify all the values. Only the one you would like to have a new value for.

setState will only add (or subsequently overwrite) values to your state. It will not re-create the whole object.

You can find the relevant documentation here. Facebook developers also thought about the exact same question you raised here and under the hood they keep the old values, and I'm quoting here:

The first argument can be an object (containing zero or more keys to update) or a function (of state and props) that returns an object containing keys to update.

like image 161
Elod Szopos Avatar answered Jan 31 '23 05:01

Elod Szopos