Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 750
Rahul Dole Avatar asked Nov 24 '14 12:11

Rahul Dole


People also ask

Can you have an object in state React?

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.

Can I store React component in state?

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.

What should be stored in React 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 .


2 Answers

  1. 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}); 
  2. You can have ordinary variables, if they don't rely on this.props and this.state.

like image 184
kiran Avatar answered Oct 15 '22 05:10

kiran


You can use ES6 spread on previous values in the object to avoid overwrite

this.setState({      abc: {             ...this.state.abc,             xyz: 'new value'            } }); 
like image 20
PranavPinarayi Avatar answered Oct 15 '22 05:10

PranavPinarayi