Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.