setState() and its forms

  • React JS
  • setState()
  • Javascript

setState() and its forms

Hello everyone, I hope everyone is doing great, so let’s start with our topic, that is the setState() and its forms in React JS. Words of caution below:

This is just the old way of changing state in React. This approach is followed when we have a class component in our react-app, nowadays we prefer functional components over class components. This blog might be helpful for the person who is working on some old projects,or wants to understand how state updates in react. I highly highly recommend you to shift on functional components, as the ReactJS docs says - “Gradual adoption strategy” for changing class based components to Functional components.

Enough of the “Word of caution talk” let’s jump back to our topic. Below is the code of a class based component.

import React,{Component} from 'react'

class Hello extends Component
{
    constructor(props)
    {
        super(props)
        this.state={count:0} // Defined state
        this.handleClick=this.handleClick.bind(this)
    }
    handleClick()
    {
        this.setState((state)=>(
            {count:state.count+1})
        ) // setState function call
    }
    render()
    {
        return(
            <div>
                <h1>Class based component hello</h1>
                <p>Count: {this.state.count}</p><br />
                <button onClick={this.handleClick}>Click me to increase Count</button> 
            </div>
        )
    }
}
export default Hello

A brief overview :-

  1. “Hello” is a class based component.
  2. On clicking the button “Click me to increase the count” invokes a method handleClick. (methods are the functions defined in class)
  3. State is defined inside the class constructor which is a javascript object the key name count is the name of our state variable which we refer down as this.state.count inside the return function.
  4. handleClick method calls are setState function.
  5. Always remember setState calls are asynchronous. (will be important later)

Our App in action

Simple react app to demonstrate state

So what does the setState function do? It just increases our count to one, simple. Let’s have a look at its syntax :-

We could have written it like this:-

The First Form

//Wrong way
this.setState({count:this.state.count+1})

A javascript object needs to be passed as a parameter to this function. The key name “count” in this object should be similar to the key name we had while we declared state in our constructor.

But, as I have mentioned before setState calls are asynchronous. React may batch multiple setState() calls into a single update for performance.

Therefore we use the second form, in this the setState () accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument. The arguments are optional, i.e I haven’t used the props argument as I don’t require it.

So :-

The Second Form

this.setState((state)=> return {count:state.count+1} )

We use the first form when we don’t require current state or current props when we are updating our state using setState().

In this case both of the forms will work but it is best to use the second form as we are using the current state to update our state. (That’s how React internally work folks)

One more important thing is that state objects are merged.

When you call setState(), React merges the object you provide into the current state. For example, your state may contain several independent variables:

constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
  }

Then you can update them independently with separate setState() calls:

// In some method where response is passed as an argument

this.setState({
        posts: response.posts
      });

and

// In some other method where response is passed as an argument
this.setState({
        comments: response.comments
      });

The merging is shallow, which means this.setState({comments}) leaves this.state.posts intact or same, but completely replaces previous this.state.comments with the new one you passed in the function.

We will learn about the coolest thing in the setState function “the callback” in our next blog here.

All blogs <--

Latest Blogs

All Blogs

© Mihir Bagchi 2021