r/javascript • sand was never meant to think • Sep 10 '24

Use react hooks in classes

https://github.com/NullVoxPopuli/classy-react/tree/main
3 Upvotes

12 comments sorted by

11

u/markus_obsidian Sep 10 '24

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.

1

u/nullvoxpopuli sand was never meant to think Sep 10 '24

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

1

u/markus_obsidian Sep 10 '24

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

1

u/nullvoxpopuli sand was never meant to think Sep 10 '24

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

4

u/markus_obsidian Sep 10 '24

No consistency whatsoever

1

u/nullvoxpopuli sand was never meant to think Sep 10 '24

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

5

u/nullvoxpopuli sand was never meant to think Sep 10 '24

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

4

u/bigtoley Sep 10 '24

Very nice!

6

u/izzlesnizzit Sep 10 '24

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.

1

u/teg4n_ Sep 10 '24

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>
    );
  }
}

1

u/nullvoxpopuli sand was never meant to think Sep 10 '24

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

2

u/romgrk Sep 10 '24

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/