I see people do that last one a lot, setting state using the previous state directly instead of using a function. They even do it in the React docs. Do you have an example of when/how this could cause problems?
You can demo the behavior in the sections titled "BAD: Don't set state that relies on the previous state without using the function of previous state" and "GOOD: When setting state that relies on the previous state, do so as a function of previous state".
Note how the bad example only changes the button's status once when the "Toggle button state 2 times" button is clicked. It goes in this order:
enabled -> disabled
enabled -> disabled
The good example correctly changes the button's status twice like this because it relies on the previous state before each state change is made:
enabled -> disabled
disabled -> enabled
You're right that the React docs show examples of incrementing a counter directly without setting it as a function of the previous state, and it drives me crazy! Haha.
The thing to note is that you will only run into trouble if the state updates are batched. So most of the time, you'll be fine writing the code without using a function. But, you will always be safe if you choose to write the code the correct way if it relies on the previous state, even if the state updates are batched. So it's safer to write it this way.
I see people do that last one a lot, setting state using the previous state directly instead of using a function. They even do it in the React docs. Do you have an example of when/how this could cause problems?
I sure do! I have some examples hosted here: tylerhawkins.info/react-component-...
You can demo the behavior in the sections titled "BAD: Don't set state that relies on the previous state without using the function of previous state" and "GOOD: When setting state that relies on the previous state, do so as a function of previous state".
Note how the bad example only changes the button's status once when the "Toggle button state 2 times" button is clicked. It goes in this order:
The good example correctly changes the button's status twice like this because it relies on the previous state before each state change is made:
You're right that the React docs show examples of incrementing a counter directly without setting it as a function of the previous state, and it drives me crazy! Haha.
The thing to note is that you will only run into trouble if the state updates are batched. So most of the time, you'll be fine writing the code without using a function. But, you will always be safe if you choose to write the code the correct way if it relies on the previous state, even if the state updates are batched. So it's safer to write it this way.
Thanks, I appreciate the examples!