Storing an object in state of a React component?
Is it possible to store an object in the state of a React component? If yes, then how can we change the value of a key in that object using setState
? I think it's not syntactically allowed to write something like:
this.setState({ abc.xyz: 'new value' });
On similar lines, I've another question: Is it okay to have a set of variables in a React component such that they can be used in any method of the component, instead of storing them in a state?
You may create a simple object that holds all these variables and place it at the component level, just like how you would declare any methods on the component.
Its very likely to come across situations where you include a lot of business logic into your code and that requires using many variables whose values are changed by several methods, and you then change the state of the component based on these values.
So, instead of keeping all those variables in the state, you only keep those variables whose values should be directly reflected in the UI.
If this approach is better than the first question I wrote here, then I don't need to store an object in the state.
-
this.setState({ abc.xyz: 'new value' });
syntax is not allowed. You have to pass the whole object.this.setState({abc: {xyz: 'new value'}});
If you have other variables in abc
var abc = this.state.abc; abc.xyz = 'new value'; this.setState({abc: abc});
You can have ordinary variables, if they don't rely on this.props and
this.state
.
You can use ES6 spread on previous values in the object to avoid overwrite
this.setState({
abc: {
...this.state.abc,
xyz: 'new value'
}
});
In addition to kiran's post, there's the update helper (formerly a react addon). This can be installed with npm using npm install immutability-helper
import update from 'immutability-helper';
var abc = update(this.state.abc, {
xyz: {$set: 'foo'}
});
this.setState({abc: abc});
This creates a new object with the updated value, and other properties stay the same. This is more useful when you need to do things like push onto an array, and set some other value at the same time. Some people use it everywhere because it provides immutability.
If you do this, you can have the following to make up for the performance of
shouldComponentUpdate: function(nextProps, nextState){
return this.state.abc !== nextState.abc;
// and compare any props that might cause an update
}