Skip to content

Instantly share code, notes, and snippets.

@frivolta
Created September 4, 2020 10:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frivolta/fbfd74c16cd62edab862f32a497bf48b to your computer and use it in GitHub Desktop.
Save frivolta/fbfd74c16cd62edab862f32a497bf48b to your computer and use it in GitHub Desktop.
createGenericContext.tsx - typing-react-context-v2
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;
};
@leonsomed
Copy link

just what i was looking for, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment