So I know that setting state in React is asynchronous and all and we set state like this:
this.setState(previousState => {
return { /* some new state that uses `previousState` */ }
});
So my question is: How can I cancel a this.setState? Let's say I use previousState to determine that I don't need to render an update. How can I cancel the setState and tell React not to re-render anything.
this.setState(previousState => {
if (/* previousState is fine */) {
// tell react not to do anything
} else {
return { /* some new state */ }
}
});
Sorry for answering my own question here, but newer React 16 allows you to cancel a
setState.source
The important distinction between returning
nulland returningpreviousStateis that returningnulldoes what likePureComponentdoes and prevents a therendermethod from being called at all.Starting from React 16, calling
setStatealways makes therendermethod fire even if you returnpreviousState.To @
bennygenel's point though, you should useshouldComponentUpdateto prevent re-renders.Update: As of React 16.8, if you're using React Hooks (this is unrelated to class components), then returning previous state from
useStatedoes, in fact, prevent the re-render altogether. See here for source