Skip to content

Instantly share code, notes, and snippets.

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;

This comment has been minimized.

Copy link

@leonsomed leonsomed commented Feb 10, 2021

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