New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Keep to single setState call? #10231

Closed
James2516 opened this Issue Jul 20, 2017 · 1 comment

Comments

Projects
None yet
2 participants
@James2516

James2516 commented Jul 20, 2017

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?

@gaearon

This comment has been minimized.

Show comment
Hide comment
@gaearon

gaearon Jul 20, 2017

Member

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!

Member

gaearon commented Jul 20, 2017

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment