Skip to content

Instantly share code, notes, and snippets.

@vezaynk
Created December 7, 2022 04:28
Show Gist options
  • Save vezaynk/c754d359dc5812493af39775e63af4d4 to your computer and use it in GitHub Desktop.
Save vezaynk/c754d359dc5812493af39775e63af4d4 to your computer and use it in GitHub Desktop.
Create HOC from Hook
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