Skip to content
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

Async render, rather than async state #3918

Closed
dubrowgn opened this issue May 20, 2015 · 3 comments
Closed

Async render, rather than async state #3918

dubrowgn opened this issue May 20, 2015 · 3 comments

Comments

@dubrowgn
Copy link

Having run into several issues related to reading state that has been set but not yet committed to the component's state, I've been wondering why setState is asynchronous at all. Wouldn't it be better to do an async render instead? This would allow you to synchronously update state all you want, with the same performance benefits of async state changes.

I'm imagining:

  1. setState mutates state immediately
  2. the same mechanism for batching state changes is invoked, only...
  3. the event originally causing state mutation simply triggers render instead

Thoughts?

@sophiebits
Copy link
Collaborator

We've gone back and forth on this; there are benefits to both. This would solve the case where you're setting your state based on your current this.state value, but not if you also read from props. See this comment:

#122 (comment)

Instead, our recommendation is to use the function form of setState so instead of

this.setState({
  alarmSet: this.state.alarmTime > 0 && this.props.elapsedTime < this.state.alarmTime
});

you write

this.setState((state, props) => ({
  alarmSet: state.alarmTime > 0 && props.elapsedTime < state.alarmTime
}));

We're not planning to change this anytime soon; any improvements will probably be along the lines of making the APIs more functional to support this better.

@tjconcept
Copy link

This is something that have wondered me too.

As a workaround I use another object to store state and use replaceState to update React's state. So far it works brilliant and has cleaned up my code considerably.
Especially in situations where I async pull data based on state and when the result comes back, only want to apply the information if the relevant state hasn't changed since (for instance search suggestions). When multiple things go into multiple async jobs that needs to be applied back into state afterwards based on multiple states still being relevant is a truly mess using setState(fn).

@gaearon
Copy link
Collaborator

gaearon commented Jan 24, 2018

Wrote some thoughts about why React works this way here: #11527 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants