Created
September 9, 2022 09:55
-
-
Save InfiniteXyy/a19a04c7e8ddfca6bdb5d640a91d056e to your computer and use it in GitHub Desktop.
Hooks in React Class Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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