3 ms·
One thing that baffles me is that no one has brought up that hooks don't have an obvious context. For instance, if I have a single app and component, and use a
by mrozbarry 6y ago
One thing that baffles me is that no one has brought up that hooks don't have an obvious context.
For instance, if I have a single app and component, and use a hook, I understand that the hook and app have some sort of implicit connection.
But what happens when I have two distinct react apps on a page - does that break the ordering that hooks require? How does a hook have any affinity to the app, or does that even matter?
I'm sure looking at the code will cause a "oh, I get it" moment, but that doesn't mean it's obvious to anyone just picking up hooks.
Honestly, I think hooks are fine, but I'd almost prefer a signature like `const MyComponent = (props, { ...hooksHere })` so there's at least a false affinity between the application and the component.
- gotofritz 6y ago> hooks don't have an obvious context. I mean, that's the whole point of hooks... they get the context of whatever host function scope they are in. That's why the 'reusable logic' spiel. So if you create a useLocalStorage hook, for example, you can then plug it into any function component and it will use. It's as if each function was an invisible class, with an invisible this.state
- acemarke 6y agoThe ordering question is literally just about how you call them within a single specific component. That component can then be used as many times as you want, in as many apps as you want. In other words, this is not legal: const [stateA, setStateA] = useState(false); if(stateA) { const [stateB, setStateB] = useState(42); } Call as many hooks as you want, in whatever sequence you want. Just make sure all the calls are at the top level of that function component, and that you don't somehow change the sequence of those from one render pass to the next. As for how they work, React already has metadata that describes each component in the tree. There's a specific field in those metadata objects that gets used for tracking internal component state, and for function components, that field stores an array / linked list of the hook calls you've made and their last saved results. See these resources for more explanations on how hooks are implemented: https://github.com/markerikson/react-redux-links/blob/master/react-hooks.md#understanding-hooks-concepts https://github.com/markerikson/react-redux-links/blob/master...