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

View all comments

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