Created
September 4, 2020 10:30
-
-
Save frivolta/fbfd74c16cd62edab862f32a497bf48b to your computer and use it in GitHub Desktop.
createGenericContext.tsx - typing-react-context-v2
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 React from "react"; | |
export const createGenericContext = <T extends unknown>() => { | |
// Create a context with a generic parameter or undefined | |
const genericContext = React.createContext<T | undefined>(undefined); | |
// Check if the value provided to the context is defined or throw an error | |
const useGenericContext = () => { | |
const contextIsDefined = React.useContext(genericContext); | |
if (!contextIsDefined) { | |
throw new Error("useGenericContext must be used within a Provider"); | |
} | |
return contextIsDefined; | |
}; | |
return [useGenericContext, genericContext.Provider] as const; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
just what i was looking for, thanks!