React JS setState

setState is an asynchronous call means if a synchronous call gets called it may not get updated at the right time like to know the current value of an object after an update using setState it may not give the current updated value on the console. To get some behavior of synchronous need to pass function instead of object to setState.

Syntax:

We can use setState() to change the state of the component directly as well as through an arrow function.

setState({ stateName : updatedStateValue })
// OR
setState((prevState) => ({
stateName: prevState.stateName + 1
}))

ReactJS setState()

All the React components can have a state associated with them. The state of a component can change either due to a response to an action performed by the user or an event triggered by the system. Whenever the state changes, React re-renders the component to the browser. Before updating the value of the state, we need to build an initial state setup. Once we are done with it, we use the setState() method to change the state object. It ensures that the component has been updated and calls for re-rendering of the component.

Table of Content

  • React JS setState
  • Steps to Create React Application:
  • Updating multiple attributes
  • Updating state values using props.
  • Updating the state using its previous value.

Similar Reads

React JS setState

setState is an asynchronous call means if a synchronous call gets called it may not get updated at the right time like to know the current value of an object after an update using setState it may not give the current updated value on the console. To get some behavior of synchronous need to pass function instead of object to setState....

Steps to Create React Application:

Step 1: Create a React application using the following command:...

Approach 1: Updating single attribute

We set up our initial state value inside constructor function and create another function updateState() for updating the state. Now when we click on the button, the latter gets triggered as an onClick event which changes the state value. We perform setState() method in our updateState() function by writing:...

Approach 2: Updating multiple attributes

...

Approach 3: Updating state values using props.

The state object of a component may contain multiple attributes and React allows using setState() function to update only a subset of those attributes as well as using multiple setState() methods to update each attribute value independently....

Approach 4: Updating the state using its previous value.

...

Contact Us