Skip to content

Instantly share code, notes, and snippets.

@Josscii
Last active April 18, 2022 05:27
Show Gist options
  • Save Josscii/626235bea5bd675215f8bd815f8d0794 to your computer and use it in GitHub Desktop.
Save Josscii/626235bea5bd675215f8bd815f8d0794 to your computer and use it in GitHub Desktop.
react typescript context helper
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