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.
State can hold any kind of JavaScript value, including objects. But you shouldn't change objects that you hold in the React state directly. Instead, when you want to update an object, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy.
Is it good practice to store whole React Components in the component state or redux state? Yes, it's optional as we could store a string in the state and render the component conditionally but in some cases, it is simpler to just store the component in the state.
In React , whenever we are working with any data, we always use state for storing that data which may be a string , number or any complex object .
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' } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With