38

I'm running into some problems with React.js and the state not being immediately set when calling setState(). I'm not sure if there are better ways to approach this, or if it really is just a shortcoming of React. I have two state variables, one of which is based on the other. (Fiddle of original problem: http://jsfiddle.net/kb3gN/4415/ you can see in the logs that it's not set right away when you click the button)

setAlarmTime: function(time) {
  this.setState({ alarmTime: time });
  this.checkAlarm();
},
checkAlarm: function() {
  this.setState({
    alarmSet: this.state.alarmTime > 0 && this.state.elapsedTime < this.state.alarmTime
  });
}, ...

When calling setAlarmTime, since this.state.alarmTime isn't updated immediately, the following call to checkAlarm sets alarmSet based on the previous value of this.state.alarmTime and is therefore incorrect.

I solved this by moving the call to checkAlarm into the callback of setState in setAlarmTime, but having to keep track of what state is actually 'correct' and try to fit everything into callbacks seems ridiculous:

setAlarmTime: function(time) {
  this.setState({ alarmTime: time }, this.checkAlarm);
}

Is there a better way to go about this? There are a few other places in my code which I reference state I just set and now I'm unsure as to when I can actually trust the state!

Thanks

0

3 Answers 3

33

Yes, setState is asynchronous, so this.state won't be updated immediately. Here are the unit tests for batching, which might explain some of the details.

In the example above, alarmSet is data computed from the alarmTime and elapsedTime state. Generally speaking, computed data shouldn't be stored in the state of the object, instead it should be computed as-needed as part of the render method. There is a section What Shouldn’t Go in State? at the bottom of the Interactivity and Dynamic UIs docs which gives examples of things like this which shouldn't go in state, and the What Components Should Have State? section explains some of the reasons why this might be a good idea.

5
  • In most cases it does make sense to have the state be as minimal as possible and to just recompute things in the render function since this.state will be completely up to date then. However, I don't think this works in my case, as this component actually has it's own update loop (using setInterval) which has to update and check its state at every tick. Therefore it's not guaranteed that render will have run in between ticks. As a workaround I implemented a wrapper on React.createClass that tracks it's own state. I'll add it as an answer here too jsfiddle.net/kb3gN/4448
    – Andrew
    Aug 6, 2014 at 1:44
  • 2
    There's a good article about the Flux architecture for RectJS here: facebook.github.io/react/docs/flux-overview.html One of the things they do is separate out the "complicated" state from the React components in the view layer, that could apply here too. Instead of putting the setInterval in the view, that would probably be something which happens in the stores, then whenever the stores update it would trigger a view re-render. The stores could be plain JS objects, without the async behaviour of setState.
    – Douglas
    Aug 6, 2014 at 8:24
  • Thanks for the explaination
    – ksharifbd
    Jul 4, 2017 at 4:13
  • Wondering if it'd be a good idea if we can move the dependent state to useEffect , that way change in the seed state will trigger update of everything else. Jan 28, 2020 at 14:03
  • my take away from question is : computed data shouldn't be stored in the state of the object!
    – emarshah
    Mar 1, 2020 at 23:50
4

As Douglas stated, it's generally not a good idea to keep computed state in this.state, but instead to recompute it each time in the component's render function, since the state will have been updated by that point.

However this won't work for me, as my component actually has its own update loop which needs to check and possibly update its state at every tick. Since we cannot count on this.state to have been updated at every tick, I created a workaround that wraps React.createClass and adds it's own internal state tracking. (Requires jQuery for $.extend) (Fiddle: http://jsfiddle.net/kb3gN/4448/)

var Utils = new function() {
  this.createClass = function(object) {
    return React.createClass(
      $.extend(
        object,
        {
          _state: object.getInitialState ? object.getInitialState() : {},
          _setState: function(newState) {
            $.extend(this._state, newState);
            this.setState(newState);
          }
        }
      )
    );
  }
}

For any components where you need up-to-date state outside of the render function, just replace the call to React.createClass with Utils.createClass.

You'll also have to change all this.setState calls with this._setState and this.state calls with this._state.

One last consequence of doing this is that you'll lose the auto-generated displayName property in your component. This is due to the jsx transformer replacing

var anotherComponent = React.createClass({

with

var anotherComponent = React.createClass({displayName: 'anotherComponent'.

To get around this, you'll just have to manually add in the displayName property to your objects.

Hope this helps

1
  • 1
    A simpler way could be to store your state entirely outside of react and pass it to react as props - then your state is always up to date, and react may not have reconciled yet which doesn't matter. Jan 10, 2015 at 22:49
2

Unsure if this was the case when question was asked, though now the second parameter of this.setState(stateChangeObject, callback) takes an optional callback function, so can do this:

setAlarmTime: function(time) {
  this.setState({ alarmTime: time }, this.checkAlarm);
},
checkAlarm: function() {
  this.setState({
    alarmSet: this.state.alarmTime > 0 && this.state.elapsedTime < this.state.alarmTime
  });
}, ...
1
  • 2
    You should never use this.state inside this.setState(...). Because this.setState(...) is asynchronous (most of the time) you can not predict what the content of this.state is at the time of execution. this.setState(prevState => ({ alarmSet: prevState.alarmTime > 0 && prevState.elapsedTime < prevState.alarmTime })); would be the right way to do it. Mar 16, 2018 at 16:32

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.