Created
February 13, 2024 12:34
-
-
Save osadi/f0bd2602e0609ca73c516ce7a01b50f7 to your computer and use it in GitHub Desktop.
Magic React Context Creator
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 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