react-use/src/factory/createStateContext.ts
Renovate Bot a27f09fd36
chore: refactoring and rearrangement.
More DRY code. Also move non-hooks to separate directories.

BREAKING CHANGE: all `create*` factories been moved to `factory` subdirectory and in case direct import should be imported like `react-use/esm/factory/createBreakpoint`
BREAKING CHANGE: `comps` directory renamed to `component`
2021-01-30 23:30:26 +03:00

24 lines
892 B
TypeScript

import { createContext, createElement, useContext, useState } from 'react';
const createStateContext = <T>(defaultInitialValue: T) => {
const context = createContext<[T, React.Dispatch<React.SetStateAction<T>>] | undefined>(undefined);
const providerFactory = (props, children) => createElement(context.Provider, props, children);
const StateProvider: React.FC<{ initialValue?: T }> = ({ children, initialValue }) => {
const state = useState<T>(initialValue !== undefined ? initialValue : defaultInitialValue);
return providerFactory({ value: state }, children);
};
const useStateContext = () => {
const state = useContext(context);
if (state == null) {
throw new Error(`useStateContext must be used inside a StateProvider.`);
}
return state;
};
return [useStateContext, StateProvider, context] as const;
};
export default createStateContext;