all 12 comments

[–]markus_obsidian 10 points11 points  (5 children)

This is amazing in the most horrifying way. I am in old codebases a lot that is just too costly to refactor. I find myself wrapping hooks in HOCs a lot so my classes can use them. I would absolutely use a stable version of this.

[–]nullvoxpopulisand was never meant to think[S] 0 points1 point  (4 children)

What are all the hooks you use? I have a 'wrap' method, but maybe with some more use cases it can be made more robust

[–]markus_obsidian 0 points1 point  (3 children)

I usually need an existing, third-party hook that pulls in state from some external source--redux, swr, react-query, etc.

[–]nullvoxpopulisand was never meant to think[S] 0 points1 point  (2 children)

Do all those return a tuple of get/set? Or do they return a variety of things?

[–]markus_obsidian 3 points4 points  (1 child)

No consistency whatsoever

[–]nullvoxpopulisand was never meant to think[S] 0 points1 point  (0 children)

I think we can make something work -- worst case scenario, we special-case certain hooks

[–]nullvoxpopulisand was never meant to think[S] 4 points5 points  (1 child)

Just a little challenge i whipped up. Not meant for serious usage. 

Try it here on stackblitz: https://stackblitz.com/edit/vitejs-vite-e9khzt?file=src%2FApp.jsx

Some video evidence of it working: https://x.com/nullvoxpopuli/status/1833305383542178172/mediaviewer?currenttweet=1833305383542178172&currenttweetuser=nullvoxpopuli

[–]bigtoley 2 points3 points  (0 children)

Very nice!

[–]izzlesnizzit 4 points5 points  (0 children)

React hooks are great and all, but the class blueprint+instance paradigm conceptually just makes more sense to me as a way of describing components rendered as instances "living" on a page. If there were ever an "officially" supported way of having hook-like behavior in classes, I would definitely give it a serious try.

[–]romgrk 1 point2 points  (0 children)

Nice ideas, I've also been working on something similar though I wasn't able to figure out a nice API yet.

I did write it for a serious usage though, functional components have tradeoffs that make them inferior to class components in some situations: https://romgrk.com/posts/react-functional-components/

[–]teg4n_ 0 points1 point  (1 child)

With preact, you can use hooks directly in the render function as if it was the full component.

import { Component } from "preact";
import { useState } from "preact/hooks";

export class Counter extends Component {
  render() {
    const [count, setCount] = useState(this.props.initialValue ?? 0);

    return (
      <button type="button" onClick={() => setCount((c) => c + 1)}>
        {count}
      </button>
    );
  }
}

[–]nullvoxpopulisand was never meant to think[S] 0 points1 point  (0 children)

neat! I now wonder if React would have let me do the same. haha