0

After reading about Controlled Components and setState I'm having problems with building a coherent mental model of React.

The example of a Controlled Component from the mentioned doc, contains following fragments relevant to my question:

handleChange(event) {
   this.setState({value: event.target.value});
}
render() {
  return (
    <input type="text" value={this.state.value} onChange={this.handleChange}/>
  )
}

The question is: since the user can perform arbitrary edit actions at high speed, and setState is presumably asynchronous, is it possible, that at moment t0, onChange was called with event.target.value='a', which caused setState({ value: 'a'}), then at moment t1 user changes text to 'b', and at moment t2, the "queued" request made via setState kicks in, and the text gets replaced with a stale value 'a'?

qbolec
  • 5,374
  • 2
  • 35
  • 44
  • You will only have one user interacting with one component at the same time. It can be ofcourse that if values come from a database that these things occur, therefore you should make sure that if you have shared data, that the saving only occurs if the user has the latest dataset, in all other cases 1 component 1 user should apply – Icepickle Jul 02 '17 at 20:56

1 Answers1

0

I believe that the correct mental model for setState should be a bit different than a vague term 'asynchronous' evokes. It's definitely not like setTimeout. It's more like debounce in that new call to setState overrides the previous one. The moment the framework decides to run render, you are guaranteed that all setStates that happened up to this moment for this control, has already been merged. Together with an assumption that each edit action causes onChange to be called synchronously, this means, that at the moment the render function is being called, this.state.value is equal to input.value.

qbolec
  • 5,374
  • 2
  • 35
  • 44
  • 3
    Are you publicly talking to yourself ? :D – trixn Jul 02 '17 at 20:18
  • Is this an addendum to your question, since it seems a bit "speculative" ;) – Icepickle Jul 02 '17 at 20:57
  • This is basically correct; `setState` will run more or less instantaneously. It just won't fire until after the function that called it has itself finished running. This causes confusion because sometimes React devs want to read from state what they've just written to state. But this is a problem with a simple solution. https://stackoverflow.com/questions/35867038/what-the-difference-of-this-state-and-this-setstate-in-reactjs/35868086#35868086 – David L. Walsh Jul 02 '17 at 23:10
  • I'm answering my own question, because 1. I like to write down results of my investigation, 2. I b e lieve that people are more eager to correct bad solution than to propose a good one, 3. I've seen others doing that and always wanted to try it :) – qbolec Jul 03 '17 at 21:19