DEV Community

loading...

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

Collapse
thawkin3 profile image
Tyler Hawkins Author

Not quite! When reversing a boolean value, we absolutely do care what the previous value was. That's the exact same logic behind incrementing a counter which you provided as a counterexample.

Doing toggleValue(!value) rather than toggleValue(value => !value) is the equivalent of doing incrementCounter(value + 1) rather than incrementCounter(value => value + 1).

In both cases, the first set of implementations is risky and can lead to bugs, while the second set of implementations will be bug free even if state updates are batched.

You can verify this by trying out the two code snippets from my article. I have them hosted here on this page under 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".

tylerhawkins.info/react-component-...

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
Collapse
urielbitton profile image
Uriel Bitton

I've used the way i showed you in many apps and it always works, never had it bug once. I'm not sure what you are doing in your example but this does not happen.

Thread Thread
thawkin3 profile image
Tyler Hawkins Author

Not quite, again. The examples are the code snippets provided in this article, and the demo is found on the site I posted. So you can easily verify this.

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, like you said. 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.