DEV Community

Discussion on: React Clean Code - Simple ways to write better and cleaner code

Collapse
 
katherinecodes profile image
Katherine Peterson

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?

Collapse
 
thawkin3 profile image
Tyler Hawkins

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:

enabled -> disabled
enabled -> disabled
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
katherinecodes profile image
Katherine Peterson

Thanks, I appreciate the examples!