Last active
April 18, 2022 05:27
-
-
Save Josscii/626235bea5bd675215f8bd815f8d0794 to your computer and use it in GitHub Desktop.
react typescript context helper
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 { createContext, useContext } from 'react' | |
export const contextFactory = <A extends unknown | null>() => { | |
const context = createContext<A | undefined>(undefined) | |
const useCtx = () => { | |
const ctx = useContext(context) | |
if (ctx === undefined) { | |
throw new Error('useContext must be used inside of a Provider with a value.') | |
} | |
return ctx | |
} | |
return [useCtx, context] as const | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment