MOCKSTACKS
EN
Questions And Answers

More Tutorials









setState()


The primary way that you make UI updates to your React applications is through a call to the setState() function. This function will perform a shallow merge between the new state that you provide and the previous state, and will trigger a re-render of your component and all decedents.

Parameters


1. updater: It can be an object with a number of key-value pairs that should be merged into the state or a function that returns such an object.

2. callback (optional): a function which will be executed after setState() has been executed successfully. Due to the fact that calls to setState() are not guaranteed by React to be atomic, this can sometimes be useful if you want to perform some action after you are positive that setState() has been executed successfully.

Usage:


The setState method accepts an updater argument that can either be an object with a number of key-value-pairs that should be merged into the state, or a function that returns such an object computed from prevState and props.

Using setState() with an Object as updater


//
// An example ES6 style component, updating the state on a simple button click.
// Also demonstrates where the state can be set directly and where setState should be used.
//
class Greeting extends React.Component {
 constructor(props) {
 super(props);
 this.click = this.click.bind(this);
 // Set initial state (ONLY ALLOWED IN CONSTRUCTOR)
 this.state = {
 greeting: 'Hello!'
 };
 }
 click(e) {
 this.setState({
 greeting: 'Hello World!'
 });
 }
 render() {
 return(
 <div>
 <p>{this.state.greeting}</p>
 <button onClick={this.click}>Click me</button>
 </div>
 );
 }

}

Using setState() with a Function as updater


//
// This is most often used when you want to check or make use
// of previous state before updating any values.
//
this.setState(function(previousState, currentProps) {
 return {
 counter: previousState.counter + 1
 };
});

This can be safer than using an object argument where multiple calls to setState() are used, as multiple calls may be batched together by React and executed at once, and is the preferred approach when using current props to set state.

this.setState({ counter: this.state.counter + 1 });
this.setState({ counter: this.state.counter + 1 });
this.setState({ counter: this.state.counter + 1 });

These calls may be batched together by React using Object.assign(), resulting in the counter being incremented by 1 rather than 3.

The functional approach can also be used to move state setting logic outside of components. This allows for isolation and re-use of state logic.

// Outside of component class, potentially in another file/module
function incrementCounter(previousState, currentProps) {
 return {
 counter: previousState.counter + 1
 };
}
// Within component
this.setState(incrementCounter);

Calling setState() with an Object and a callback function


//
// 'Hi There' will be logged to the console after setState completes
//
this.setState({ name: 'John Doe' }, console.log('Hi there'));


Conclusion

In this page (written and validated by ) you learned about React setState . What's Next? If you are interested in completing React tutorial, your next topic will be learning about: React State Events And Managed Controls.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.