4 ms·
> React knows which component is rendering at any point in time — so it knows which component useState() call corresponds to. Personally, I think that may be t
by dvlsg 8y ago
> React knows which component is rendering at any point in time — so it knows which component useState() call corresponds to.
Personally, I think that may be the piece that makes it feel a bit magical. With `this.setState()`, usage of `this` makes me feel like I know how the component and the state are linked.
With hooks, however, there's no obvious link to the component in the code. I'm grabbing `useState` off of the shared react module, `useState` is not passed into the component, and I don't have to reference the component itself at any point while using hooks. The new sets of rules you have to follow to make things line up correctly play a part, as well.
Of course that may be how `this.setState()` does it anyways - you know better than I do, obviously. Maybe the usage of `this.setState()` made me feel confident in something I didn't actually understand under the hood. But at least for me, that's why `useState()` feels a bit magical at first glance compared to `this.setState()`. Not _too_ magical, and not enough to scare me away from using hooks, but still a bit.
- danabramov 8y agoYeah I totally get that. Conceptually Hooks are modeled as "algebraic effects" feature from languages like Eff and Koka. Those are essentially like resumable exceptions. With that conceptual model, `useState` is like a `throw` that goes back into React "up the stack", and then goes back into your code. Of course that's not how it works for perf and other reasons (there's no resumable exceptions in JS). But this may help the conceptual model around how we know which component it is.