import { Dispatch , SetStateAction , useCallback , useRef , useState } from 'react' ; export interface StateMediator < S = any > { ( newState ) : S ; ( newState , dispatch ) : void ; } export type UseMediatedStateReturn < S = any > = [ S , Dispatch < SetStateAction < S > > ] ; export function useMediatedState < S = undefined > ( mediator ) ; export function useMediatedState < S = any > ( mediator , initialState ) ; export function useMediatedState < S = any > ( mediator , initialState ? ) { const mediatorFn = useRef ( mediator ) ; const [ state , setMediatedState ] = useState < S > ( initialState ! ) ; const setState = useCallback ( ( newState ) => { if ( mediatorFn . current . length === 2 ) { mediatorFn . current ( newState , setMediatedState ) ; } else { setMediatedState ( mediatorFn . current ( newState ) ) ; } } , [ state ] ) ; return [ state , setState ] ; }