Permalink
Branch: master
Find file Copy path
868466a Jan 17, 2019
1 contributor

Users who have contributed to this file

44 lines (36 sloc) 1.04 KB
import * as React from "react";
// istanbul ignore next
function warnNoProvider() {
// eslint-disable-next-line no-console
console.warn("[constate] Missing Provider");
}
// istanbul ignore next
const canUseProxy =
process.env.NODE_ENV === "development" && typeof Proxy !== "undefined";
// istanbul ignore next
const defaultValue = canUseProxy
? new Proxy({}, { get: warnNoProvider, apply: warnNoProvider })
: {};
function createContainer<P, V>(
useValue: (props: P) => V,
createMemoInputs?: (value: V) => any[]
) {
const Context = React.createContext(defaultValue as V);
const Provider = (props: { children?: React.ReactNode } & P) => {
const value = useValue(props);
// createMemoInputs won't change between renders
const memoizedValue = createMemoInputs
? React.useMemo(() => value, createMemoInputs(value))
: value;
return (
<Context.Provider value={memoizedValue}>
{props.children}
</Context.Provider>
);
};
return {
Context,
Provider
};
}
export default createContainer;