import { useState } from 'react' ; import { IHookStateInitAction , IHookStateSetAction , resolveHookState } from '../misc/hookState' ; import useEffectOnce from '../useEffectOnce' ; import useIsomorphicLayoutEffect from '../useIsomorphicLayoutEffect' ; export function createGlobalState < S = any > ( initialState ) ; export function createGlobalState < S = undefined > ( ) ; export function createGlobalState < S > ( initialState ? ) { const store = { state : initialState instanceof Function ? initialState ( ) : initialState , setState ( nextState ) { store . state = resolveHookState ( nextState , store . state ) ; store . setters . forEach ( ( setter ) => setter ( store . state ) ) ; } , setters : [ ] , } ; return ( ) => { const [ globalState , stateSetter ] = useState < S | undefined > ( store . state ) ; useEffectOnce ( ( ) => ( ) => { store . setters = store . setters . filter ( ( setter ) => setter !== stateSetter ) ; } ) ; useIsomorphicLayoutEffect ( ( ) => { if ( ! store . setters . includes ( stateSetter ) ) { store . setters . push ( stateSetter ) ; } } ) ; return [ globalState , store . setState ] ; } ; } export default createGlobalState ;