Skip to content

Instantly share code, notes, and snippets.

@osadi
Created February 13, 2024 12:34
Show Gist options
  • Save osadi/f0bd2602e0609ca73c516ce7a01b50f7 to your computer and use it in GitHub Desktop.
Save osadi/f0bd2602e0609ca73c516ce7a01b50f7 to your computer and use it in GitHub Desktop.
Magic React Context Creator
import type { Context, PropsWithChildren } from 'react';
import React from 'react';
function createUseContext<T>(FilterContext: Context<T | null>, noContextMessage: string) {
return () => {
const context = React.useContext(FilterContext);
if (!context) {
throw new Error(noContextMessage);
}
return context;
};
}
function createProvider<Value, ProviderProps>(
Context: Context<Value | null>,
value: Value | null,
provider?: (value: Value | null, props: ExplicitAny) => Value
) {
return function ContextProvider({ children, ...props }: PropsWithChildren<ProviderProps>) {
return (
<Context.Provider value={provider?.(value, props) || value}>{children}</Context.Provider>
);
};
}
export function createContext<T = unknown, ProviderProps = unknown>(
value: T | null,
noContextMessage: string,
provider?: (value: T | null, props: ProviderProps) => T
) {
const Context = React.createContext<T | null>(value);
const ContextProvider = createProvider<T, ProviderProps>(Context, value, provider);
const useContext = createUseContext<T>(Context, noContextMessage);
return {
Context,
ContextProvider,
useContext
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment