4 ms·
It seems like the main benefit the authors of hooks get at is being able to encapsulate a library's logic into hooks that you can reuse, so eg. you could do `co
by nikki93 6y ago
It seems like the main benefit the authors of hooks get at is being able to encapsulate a library's logic into hooks that you can reuse, so eg. you could do `const [data, loading] = useQuery('some query');` and the query is aware of lifetime etc. without needing to use mixins or multiple inheritance or traits or something else like the component or ECS paradigms from game engines (that each have their pros and cons).
You could have a stateful `this.query` object in your class, but you basically have to spread the code for that around (calling mount / unmount handlers or events) vs. just mentioning it in one place and having it be able to use more hooks internally etc.
It's basically like an `import` statement for your component.
- spankalee 6y agoThis is my point about attacking composition with what we have for classes - because reuse and composition are problems not limited to UI widgets. Your query example is easily handled by a mixin: // Queryable provides this.data and this.loading and // hooks into the lifecycle class MyComponent extends Queryable(Component) { query = 'some query'; render() { // ... } } You can also use helper objects: class MyComponent extends Component { query = new Query(this, 'some query'); render() { // ... } connectedCallback() { this.query.connect(); } } I understand that you have to wire up the lifecycle methods this way, but it's at least low-magic and easily understandable. I don't mind it. And even though decorators aren't standard yet, they can be used for composition too. My point is that these problems aren't unique to React and deserve patters and solutions for all JavaScript programming. React is statefull and object-based under the hood, but just trying to hide it.