Created
May 2, 2023 20:34
-
-
Save yleflour/2851b8a12a47288b7553d5a3d6f49aa8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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