Skip to content

Instantly share code, notes, and snippets.

@knjname
Last active March 26, 2021 08:27
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 knjname/9a06ba37097ef128b13b8853d7208d9c to your computer and use it in GitHub Desktop.
Save knjname/9a06ba37097ef128b13b8853d7208d9c to your computer and use it in GitHub Desktop.
import React, { useContext } from "react";
const map = new Map<any, any>();
export const createGlobalStore = <T>(
key: any,
generateStore: (prevStore: T | undefined) => T
) => {
const store = generateStore(map.get(key));
map.set(key, store);
const context = React.createContext<T>(store);
return {
Provider: context.Provider,
Consumer: context.Consumer,
useStore: () => useContext(context),
getStore: () => map.get(key),
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment