Skip to content

Instantly share code, notes, and snippets.

@yleflour
Created May 2, 2023 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yleflour/2851b8a12a47288b7553d5a3d6f49aa8 to your computer and use it in GitHub Desktop.
Save yleflour/2851b8a12a47288b7553d5a3d6f49aa8 to your computer and use it in GitHub Desktop.
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