3 ms·
These "mistakes" are presented as React specific but I think most of them are general programming mistakes. Or perhaps JavaScript mistakes if your please, since
by dajonker 4y ago
These "mistakes" are presented as React specific but I think most of them are general programming mistakes. Or perhaps JavaScript mistakes if your please, since not all languages allow you to make all of the mistakes with mutating and using state.
For example the "Accessing state after changing it" has absolutely nothing to do with React or async code, and everything to do with the scope of the count variable and how JavaScript passes numbers by value.
- jagged-chisel 4y agoWithout React (or a similar framework) JavaScript makes the assignment immediately. It’s not like the language has some special handling compared to other languages in this regard. React, otoh, provides methods that access and update state. React’s handling of changing state using these methods is to queue the change, not to update it immediately.
- dajonker 4y agoI'm talking about this specific piece of code: function handleClick() { setCount(count + 1); console.log({ count }); } Since count is enclosed within the function, it could be mutated by _anything_. In isolation, you can't really be sure of what setCount does, since the "count + 1" statement passes a completely new value unrelated to count. If setCount didn't have any side effects, it is an obvious mistake to assume the value of "count" would have changed. So if the intention is to log the incremented count, it is bad code in any situation, React or not.
- jagged-chisel 4y agoWithout further context, that looks like a property setter. There’s absolutely nothing wrong with thinking that the property setter sets the property immediately. What you’re saying amounts to “functions/methods can do whatever they want, and assuming they do what they claim to do is an obvious mistake.”