4 ms·
One thing that looks 'magical' is how does the setWhatever function lets React know that state has changed and has to re-render? Is there any info/writeup on th
by palerdot 8y ago
One thing that looks 'magical' is how does the setWhatever function lets React know that state has changed and has to re-render? Is there any info/writeup on this anywhere?
- FLGMwt 8y agoThe component renders any time the setWhatever function is called, similar to this.setState() in class components. The presumption is anything that you're storing in state is depended on by the component. If it's not, it doesn't make sense to have it in state anyway.
- danabramov 8y agoPretty much the same way as this.setState in a class does. React knows which component is rendering at any point in time — so it knows which component useState() call corresponds to. I think this explanation is quite accessible: https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e https://medium.com/@ryardley/react-hooks-not-magic-just-arra...
- 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.