Last active
October 27, 2021 23:27
-
-
Save jasmo2/1775785888ed75c8588edc1e51c3a6c2 to your computer and use it in GitHub Desktop.
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 { useContext } from "react" | |
export function useContextFactory<T>(name: string, context: React.Context<T>) { | |
return () => { | |
const ctx = useContext(context) | |
if (ctx === undefined) { | |
throw new Error( | |
`use${name}Context must be used withing a ${name}ContextProvider.` | |
) | |
} | |
return ctx as NonNullable<T> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment