DEV Community

Cover image for Why Do We Use this.setState()?

Why Do We Use this.setState()?

Tori Crawford on October 03, 2019

During my React assessment I was asked the question why we should use this.setState() and not just this.state.KEY = VALUE. This question stumped me...
Collapse
 
joetex profile image
Joel Ruiz • Edited

Also setState under the covers uses Object.assign which let's you use partial objects like {a:10} while this.state has {b:20}. this.state would end up with {a:10, b:20}.

Collapse
 
oinak profile image
Oinak

Hello!, Great article, thanks for sharing

I am also investigating these matters nowadays and recently discovered that if you have

class Foo extend Component {
  constructor(props){
    super(props)
    this.state = { foo: 1 }
  }
//...

And you are:

  • using modern js or babel
  • not doing extra stuff on the constructor

then, you can do:

class Foo extend Component {
  state = { foo: 1 }
//...

and it works the same.

I hope it helps.

Collapse
 
ducksauce88 profile image
ducksauce88

Great article! I'm currently looking for a job and while I know how to use what I know, sometimes I am not able to explain why. Thanks!!

Collapse
 
mjoycemilburn profile image
MartinJ

That's a really helpful post. You have a great writing talent. Keep it up - I think that writing clear English is actually much more challenging than writing smart code!