Skip to content

Instantly share code, notes, and snippets.

@InfiniteXyy
Created September 9, 2022 09:55
Show Gist options
  • Save InfiniteXyy/a19a04c7e8ddfca6bdb5d640a91d056e to your computer and use it in GitHub Desktop.
Save InfiniteXyy/a19a04c7e8ddfca6bdb5d640a91d056e to your computer and use it in GitHub Desktop.
Hooks in React Class Component
import React, { useState } from "react";
function defineHooks<T extends unknown>(hooks: () => T) {
type Params = ReturnType<typeof hooks>;
return (props: { children: (params: Params) => JSX.Element }) => {
const { children } = props;
return children(hooks());
};
}
class App extends React.Component {
render(): React.ReactNode {
const Provider = defineHooks(() => {
const [count, setCount] = useState(0);
return { count, setCount };
});
return (
<Provider>
{({ count, setCount }) => {
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}}
</Provider>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment