JainZz
JainZz

Reputation: 612

Best practice for setState in React?

Which is the better way to setState in reactJs.

case 1: to store separate state variables

this.setState({
  value1: 'value1',
  value2: 'value2',
  ....
  valueN:'valueN'
})

case 2: to store in state object

this.setState({
  values: {
    ...values,
    [key]: value
  }
});

Is there any performance issue in both cases?

Thanks.

Upvotes: 1

Views: 959

Answers (2)

stackdave
stackdave

Reputation: 7094

in your case 1, you are only assigning values, and in the case 2, you are using a predefined value adding a a new element.

Generally you can mix key and values, and make operations inside setStates

this.setState({
  value1: {
    ...values,
    [key]: value
  },
  value2: 'value2',
  value3:  [...otherArrayValues, newValue]
  loading: false,
  id: '',
  ....
  valueN:'valueN'
})

but in your case it's look you want to save data objects in your state (list with associative), so it's a array that contains objects better to separate the value accord to object, and make the operations before with the array of objects before .setState

example:

const myNewCountryValues = [
  "USA" => { id: 1, name: "United States"},
  "FR"  => { id: 2, name: "France"},
]

then you can manage in a clean way the array:

newCountry = { id: 3, name: "Germany"} ;


myNewCountryValues.push ( newCountry );

with associative.key:

myNewCountryValues["GE"] = newCountry ;

update the state:

this.setState({ countries: myNewCountryValues});

or in one line:

this.setState({ countries: [...myNewCountryValues, newCountry]});

Upvotes: 1

Razat Patkar
Razat Patkar

Reputation: 91

It depends on your use. For example, if the data belongs to only one thing or one concept keep it in a single variable inside the state and if they belong to different things do the reverse. Hope this will help.

Upvotes: 1

Related Questions