Hacker News new | ask | show | jobs
by theteapot 1190 days ago
> Hooks let you colocate logic that, in class components, would need to be split across multiple lifecycle methods.

I think the obvious OO alternative to hooks would have been this:

    class MyComponent {
        constructor() {
            this.attachBehaviour(new MyBehaviour(this));
            this.attachBehaviour(new MyOtherBehaviour(this));
        }

        render() { /* ... */ }
    }
    
    class MyBehaviour implements ComponentLifeCycleHooks {
        componentDidMount() { /* ... */ }
        componentWillUnmount() { /* ... */ }
        componentDidUpdate() { /* ... */ }
    }
Weird React didn't even seem to consider when they went to hooks. Would be possible to implement yourself though.

I'm not saying this is better than hooks / "composable" / "functional" API (I quite like Vue's composable API) but it's less of a departure from class based components.

2 comments

Departure from class based components was one of the motivations behind hooks, those are:

1. It’s hard to reuse stateful logic between components

2. Complex components become hard to understand

3. Classes confuse both people and machines

See https://legacy.reactjs.org/docs/hooks-intro.html#motivation for details. Agree or not, but it is a very intentional and well motivated direction.

Above was OO an based solution to #1, and arguably #2. Many would argue hooks did nothing to solve #2 and may have made things worse.

> Agree or not, but it is a very intentional and well motivated direction.

Agree with problem exists (roughly), disagree on solution.

Interesting you assume they didn't consider this. They probably did.

How do this two behaviours compose together/interact with each other?

I made no such assumption. I've just never seen it discussed, where as, for example, I've seen "mixins" discussed and dismissed (justifiably) as an alt.

> How do this two behaviours compose together/interact with each other?

What?