well i cant really explain well but this article explains it really well.
especially following headings:
So what does this mean for React
The Arrow Function
like arrow function is feature of ES6 which is already bounded with this keywork. so we dont have to use it all the time and it looks much more cleaner
I mean to get technical, setState is synchronous, but its internal effect of updating state is not. Once you call it, you donât know when it will get updated.
So, in the above example, if the count starts at 0, what will it be after these two lines? It depends. If the first line finishes before the second line starts, it will be two. If the second line starts before the first line finishes, it will be 1. That is an issue. The functional version of setState fixes that.
Should you always use the functional form? You can, if you want. I will sometimes use the object form if the new state is not dependent in any way on the old state and if there is no chance of it getting fired off in rapid succession.
I wonder if the problem described in this curriculum ⌠that âusing this.state in setState may not refer to the latest state because the state is asynchronousâ still occurs in this case.
It is hard to tell what you are referring to there. If you mean the toggle function, then yes, potentially, because the new state is dependent on the old state. If there were separate functions for âonâ and âoffâ then it would be less of an issue. They would be idempotent in that case so it doesnât matter if the âonâ function runs once or 100 times and in what order.
When in doubt, use the function version. you can always use it. There is no downside.
Thank you for your reply.
I was currently studying mainly class components, but if I use functional components, does that mean I wonât have this state related problem?
Functional components handle state differently, but similarly. You will have a similar issue in that with functional components you use hooks (instead of lifecycle methods) and those donât update until a rerender so you can still have un-updated data. And you still have the choice of objective and functional state setters, just like with setState. So, yeah, similar issues.
But it canât hurt to learn class components. Just keep in mind that most modern React development doesnât use those (preferring functional components with hooks). You still need to know class components - youâll see them in old code - but I wouldnât spend too long on them. But you also transfer over a lot of the basic concepts from class components so itâs not a complete waste.
Thank you very much for your kind reply.
I hope to grasp the basic concepts in learning class components and start learning functional components as soon as possible.