Managing React State: Why calling state at the right time makes for a wonderful walk in the park

Girl standing on wooden arched bridge in a park, with green trees in the background.

You and your best friend made an appointment to meet for a walk in the park, and then you rescheduled to a new date. The next day, you checked your calendar, biked to your rendezvous… But where is she? Didn’t you guys agree to meet at this time? You stand there puzzled, while your friend is at home getting ready for dinner. That’s because you and your friend agreed to meet tomorrow!

This is what it’s like to try and pull values from your component’s state at the wrong time. Because setState is asynchronous in certain situations (such as event handlers), it means that if you make a call to state using an onClick event, you can’t get values right after calling setState like this:

this.state = {
    newDate: 'Oct 31'
}
...
let updatedDate = 'Jan 1';
...
onSubmit(updatedDate){
    this.setState({newDate: updatedDate});
    const {newDate} = this.state;
    alert(`Your new appointment date is ${newDate}`);
}
...
<MyComponent
    onClick={this.onSubmit}
/>

If we try this, our alert will read “Your new appointment date is Oct 31”. Since the state has not yet been updated, React is reading us the current state’s value. React will wait until all the components have loaded to update the state.

So what would we do in this case? Well the answer is simple: don’t try to create a variable from state in the function, just use the argument passed to the function:


onSubmit(updatedDate){
    this.setState({newDate: updatedDate});
    alert(`Your new appointment date is ${updatedDate}`);
}

It’s a simple answer, but it had me confused for several hours!

So next time you go to meet your friend in the park, make sure that you update the calendar with the new date that she tells you on the phone, and don’t update with the date already on the calendar!

Two girl friends in park throwing yellow and orange leaves in the air in fall. Featuring leafless trees and hills in the background.
Noémi Macavei-Katócz, Unsplash

References
React Docs (2020). “Component state.” [Web]. React. Available at: https://reactjs.org/docs/faq-state.html

Girl on bridge photo credit: Soroush Karimi, Unsplash

Subscribe to new blog posts