Skip to content

Instantly share code, notes, and snippets.

@malj
Last active June 5, 2023 17:11
Show Gist options
  • Save malj/463d5473b13864d7dbd2d256ef0f3577 to your computer and use it in GitHub Desktop.
Save malj/463d5473b13864d7dbd2d256ef0f3577 to your computer and use it in GitHub Desktop.
Singleton React hook (via Context API)
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