r/javascript • u/nullvoxpopuli sand was never meant to think • Sep 10 '24
Use react hooks in classes
https://github.com/NullVoxPopuli/classy-react/tree/main5
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¤ttweetuser=nullvoxpopuli
4
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/
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.