UNPKG

@raulpesilva/re-state

Version:

easy way to create a shared state to the entire application

30 lines (28 loc) 947 B
import { useCallback, useDebugValue, useState } from 'react'; import { store } from './store'; import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'; export function useReState(key, initialValue) { var makeState = useCallback(function (value) { if (store.has(key)) { return store.get(key); } else { store.setWithoutNotify(key, value); return store.get(key); } }, [key]); var setState = useCallback(function (newValue) { store.set(key, newValue); }, [key]); var _useState = useState(makeState(initialValue)), reStateValue = _useState[0], setReStateValue = _useState[1]; useDebugValue(makeState(initialValue)); useIsomorphicLayoutEffect(function () { var unSub = store.subscribe(key, function () { setReStateValue(store.get(key)); }); return unSub; }, [initialValue, key]); return [reStateValue, setState]; } useReState.displayName = 'useReState';