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 React, { useContext } from "react"; | |
import { createContext } from "react"; | |
export const contextFactory = <TParams, TStore>(useStore: (args: TParams) => TStore) => { | |
const Context = createContext<TStore>(null as TStore); | |
const useStoreContext = () => useContext(Context); | |
const Provider = ( | |
props: | |
| { store: TStore; args?: never; children: React.ReactNode } | |
| { store?: never; args: TParams; children: React.ReactNode } | |
) => { | |
if (props.store) | |
return <Context.Provider value={props.store}>{props.children}</Context.Provider>; | |
const store = useStore(props.args as TParams); | |
return <Context.Provider value={store}>{props.children}</Context.Provider>; | |
}; | |
return { Context, useStoreContext, Provider }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment