MOCKSTACKS
EN
Questions And Answers

More Tutorials









React setState pitfalls


You should use caution when using setState in an asynchronous context. For example, you might try to call setState in the callback of a get request:

class MyClass extends React.Component {
 constructor() {
 super();
 this.state = {
 user: {}
 };
 }
 componentDidMount() {
 this.fetchUser();
 }
 fetchUser() {
 $.get('/api/users/self')
 .then((user) => {
 this.setState({user: user});
 });
 }
 render() {
 return <h1>{this.state.user}</h1>;
 }
}

This could call problems - if the callback is called after the Component is dismounted, then this.setState won't be a function. Whenever this is the case, you should be careful to ensure your usage of setState is cancellable.

In this example, you might wish to cancel the XHR request when the component dismounts:

class MyClass extends React.Component {
 constructor() {
 super();
 this.state = {
 user: {},
 xhr: null
 };
 }
 componentWillUnmount() {
 let xhr = this.state.xhr;
 // Cancel the xhr request, so the callback is never called
 if (xhr && xhr.readyState != 4) {
 xhr.abort();
 }
 }
componentDidMount() {
 this.fetchUser();
 }
 fetchUser() {
 let xhr = $.get('/api/users/self')
 .then((user) => {
 this.setState({user: user});
 });
 this.setState({xhr: xhr});
 }
}

The async method is saved as a state. In the componentWillUnmount you perform all your cleanup - including canceling the XHR request.

You could also do something more complex. In this example, I'm creating a 'stateSetter' function that accepts the this object as an argument and prevents this.setState when the function cancel has been called:

function stateSetter(context) {
 var cancelled = false;
 return {
 cancel: function () {
 cancelled = true;
 },
 setState(newState) {
 if (!cancelled) {
 context.setState(newState);
 }
 }
 }
}
class Component extends React.Component {
 constructor(props) {
 super(props);
 this.setter = stateSetter(this);
 this.state = {
 user: 'loading'
 };
 }
 componentWillUnmount() {
 this.setter.cancel();
 }
 componentDidMount() {
 this.fetchUser();
 }
 fetchUser() {
 $.get('/api/users/self')
 .then((user) => {
 this.setter.setState({user: user});
 });
 }
 render() {
 return <h1>{this.state.user}</h1>
 }
}

This works because the cancelled variable is visible in the setState closure we created.


Conclusion

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



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.