Created
December 7, 2022 04:28
-
-
Save vezaynk/c754d359dc5812493af39775e63af4d4 to your computer and use it in GitHub Desktop.
Create HOC from Hook
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, { useContext, createContext } from "react"; | |
function createHOCFromHook<T,>(cb: () => T) { | |
const Context = createContext<T>(null as T); | |
const withProvider = <T,>(Component: React.ComponentType<T>) => | |
function (props: T & JSX.IntrinsicAttributes) { | |
return ( | |
<Context.Provider value={cb()}> | |
<Component {...props} /> | |
</Context.Provider> | |
); | |
}; | |
return { | |
withProvider, | |
Provider: Context.Provider, | |
Consumer: Context.Consumer, | |
useHook: () => useContext(Context) | |
}; | |
} | |
function createHOCFromHookWithArgs<T,A extends []>(cb: (...args: A) => T) { | |
const Context = createContext<T>(null as T); | |
const withProvider = (...args: A) => <T,>(Component: React.ComponentType<T>) => | |
function (props: T & JSX.IntrinsicAttributes) { | |
return ( | |
<Context.Provider value={cb(...args)}> | |
<Component {...props} /> | |
</Context.Provider> | |
); | |
}; | |
return { | |
withProvider, | |
Provider: Context.Provider, | |
Consumer: Context.Consumer, | |
useHook: () => useContext(Context) | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment