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
.
Minor changes to setState behavior:
- Calling
setState
withnull
no longer triggers an update. This allows you to decide in an updater function if you want to re-render.- Calling
setState
directly in render always causes an update. This was not previously the case. Regardless, you should not be callingsetState
from render.setState
callback (second argument) now fires immediately aftercomponentDidMount
/componentDidUpdate
instead of after all components have rendered.
source
The important distinction between returning null
and returning previousState
is that returning null
does what like PureComponent
does and prevents a the render
method from being called at all.
Starting from React 16, calling setState
always makes the render
method fire even if you return previousState
.
To @bennygenel
's point though, you should use shouldComponentUpdate
to 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 useState
does, in fact, prevent the re-render altogether. See here for source
The idiom for "tell React not to do anything" is "return the previous state". It's up to React's internal management to determine that there are no actual changes to the DOM, and nothing will be visible to the user. In particular, the default shouldComponentUpdate
will return false if the two objects are identical.
So the only thing you need is:
return previousState
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With