Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cancel a `this.setState`?

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 */ }
  }
});
like image 791
Rico Kahler Avatar asked Sep 06 '17 14:09

Rico Kahler


2 Answers

Sorry for answering my own question here, but newer React 16 allows you to cancel a setState.

Minor changes to setState behavior:

  • Calling setState with null 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 calling setState from render.
  • setState callback (second argument) now fires immediately after componentDidMount / 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

like image 116
Rico Kahler Avatar answered Oct 02 '22 14:10

Rico Kahler


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;

like image 21
Joshua Engel Avatar answered Oct 02 '22 12:10

Joshua Engel