TS friendly React Context
import { createContext, useContext } from 'react'; | |
import type { Provider } from 'react'; | |
export function createCtx<A extends unknown | null>(): readonly [() => A, Provider<A | undefined>] { | |
const ctx = createContext<A | undefined>(undefined); | |
function useCtx() { | |
const c = useContext(ctx); | |
if (c === undefined) throw new Error('useCtx must be inside a Provider with a value'); | |
return c; | |
} | |
return [useCtx, ctx.Provider] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment