Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[question] state object and setState() #10636

Closed
bhutaninitin opened this issue Sep 7, 2017 · 1 comment
Closed

[question] state object and setState() #10636

bhutaninitin opened this issue Sep 7, 2017 · 1 comment

Comments

@bhutaninitin
Copy link

Suppose if I have 100 objects and each maps to 100 different DOM components. Which of the following coding practice helps react setState() save work:

Practice 1:

this.state={allObj: {"one": true, "two": true, "three": false, "four": true}}

updateState(val,key){
var tmpobj=this.state.allObj;
tmpobj[key]=val;
this.setState({allObj: tmpobj})
}

OR

Practice 2:

this.state ={
one: true,
two: true,
three: false,
four: true
}

updateStateOne(val)
{
this.setState({one: val})
}

updateStateTwo(val)
{
this.setState({Two: val})
}
@jquense
Copy link
Contributor

jquense commented Sep 7, 2017

In most cases they are equivalent because React batches the setState calls. Technically Practice 1 is going to be faster, and more memory efficient (probably) because you are mutating the original state object before setting it again. However its also less safe, and not recommended to mutate the state object in-place like that. I wouldn't worry about it unless you are able to measure some noticeable bottleneck there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants