Hacker News new | ask | show | jobs
by eyelidlessness 2017 days ago
> What would it have looked like if class-based components got a v2 rev instead? I feel like a lot of the crazy with class-based components came from the myriad low-level callbacks. useEffect() is a better abstraction, but it seems like some sort of class-based analogue could have been created (perhaps registering effects in the constructor).

This certainly seems like it would have been a better design, it would definitely be easier to reason about. Or even just an additional function boundary between where hooks are called and where JSX is rendered (semantically it’s basically the same thing but less verbose). Or even just changing the hooks interface to be a factory, accepting a component function as a parameter, where that component receives props `P & HookState<FooHook>`, which probably would be a lighter lift for React’s implementation because it could simply be a wrapper around the current behavior.

1 comments

You could trial implement some of these ideas as a design pattern in the existing Hooks design as essentially an "HOC".

    interface HookClassComponent {
        render(): React.JSX
    }

    interface HookClassComponentConstructor {
        new(): HookClassComponent // all hooks should happen here
    }

    function renderHookClass(hookClass: HookClassComponentConstructor) {
        const instance = new hookClass()
        return hookClass.render()
    }
That said, if you were to actually try to build HookClassComponents like this you'd see some of why React presumably didn't bother to include an "HOC" like this. A lot of the hooks rely on simple arrow function closures around variables and it would presumably be a lot easier to make mistakes in handling that temporary mutable state directly as class (private) properties than in single function scopes, and there would presumably be a lot more pressure to make such state modifiable by outside components.

I'd be curious though to see more people try an "HOC" like this, though, and report back what sort of results they get.

I’ve thought about wrapping it as a proof of concept when I have some space to work on it. But I’m more inclined to try out a factory style interface (outer function initializes hooks and returns a function component that accepts the props for the base component plus state from the hooks).

I think it would fit more my preferred style as well as the kind of interface that people find attractive in hooks. It would work well with generics in TypeScript. And it wouldn’t be as fussy about the weird implicit behavior of component naming that came with wrapped/generated classes and decorators in past experiments with composition in past React fads.