Setting state in Class-based Components

Published: 20 Dec 2021 | Last updated 20 December 2021

We don't change the state directly, instead we use setState method which comes from the parent class React.Component

We can pass the setState method two different things:

  • A new version of state i.e. an object
  • Any time we care about the previous state, we pass a function to it and that function is going to receive in its parameter the previous version of the state and we can then return a new object based on the previous one

Note: Anytime we create a class method that we want to use setState on, we need to bind the method to our own class inside the constructor like:

this.methodName = this.methodName.bind(this)
  • Techtud Admin
  • @techtud
  • Senior editor at techtud

What to read next

Sounds rather exhausting, right?Well, it was indeed exhausting! Many of the times but when I analyze what all I was able to accomplish in a year's

Here is a time worthy documentation: