React: [Question] Keep to single setState call?

Created on 20 Jul 2017  路  1Comment  路  Source: facebook/react

class App extends Component() {
  fn1() {
    this.setState({a});
    fn2()
  }
  fn2() {
    this.setState({b});
  }
}

Is it guaranteed that calling fn1 will only trigger a single re-render?
Is it a better practise to pass a to fn2 and keep it to a single setState({a, b}) call?

Most helpful comment

This is implementation detail and may change in future versions.

In current release, they will be batched together if you are inside a React event handler. React batches all setStates done during a React event handler, and applies them just before exiting its own browser event handler.

With current version, several setStates outside of event handlers (e.g. in network responses) will not be batched. So you would get two re-renders in that case.

There exists a temporary API to force batching. If you write ReactDOM.unstable_batchedUpdates(() => { this.fn1(); }); then both calls will be batched. But we expect to remove this API in the future and instead batch everything by default.

I hope this helps!

>All comments

This is implementation detail and may change in future versions.

In current release, they will be batched together if you are inside a React event handler. React batches all setStates done during a React event handler, and applies them just before exiting its own browser event handler.

With current version, several setStates outside of event handlers (e.g. in network responses) will not be batched. So you would get two re-renders in that case.

There exists a temporary API to force batching. If you write ReactDOM.unstable_batchedUpdates(() => { this.fn1(); }); then both calls will be batched. But we expect to remove this API in the future and instead batch everything by default.

I hope this helps!

Was this page helpful?
0 / 5 - 0 ratings