Last active
June 5, 2023 17:11
-
-
Save malj/463d5473b13864d7dbd2d256ef0f3577 to your computer and use it in GitHub Desktop.
Singleton React hook (via Context API)
This file contains 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 { ComponentType, createElement, createContext, useContext } from "react" | |
export const createSingletonHook = <P, S>( | |
useHook: (props: P) => S | |
): [() => S, ComponentType<P>] => { | |
const Context = createContext<S | undefined>(undefined) | |
const SingletonHookProvider: ComponentType<P> = ({ | |
children, | |
...props | |
}) => { | |
const value = useHook(props as P) | |
return createElement(Context.Provider, { value }, children) | |
} | |
const useSingletonHook = (): S => { | |
const value = useContext(Context) | |
if (typeof value === "undefined") { | |
throw new Error( | |
"Component must be a wrapped in a singleton hook Provider" | |
) | |
} | |
return value | |
} | |
return [useSingletonHook, SingletonHookProvider] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment