import { useCallback , useRef , useState , SetStateAction , Dispatch } from "react" ; const isFunction = < S > ( setStateAction ) : setStateAction is ( prevState : S ) => S => typeof setStateAction === "function" ; type ReadOnlyRefObject < T > = { readonly current : T ; } ; type UseStateRef = { < S > ( initialState ) : [ S , Dispatch < SetStateAction < S > > , ReadOnlyRefObject < S > ] ; < S = undefined > ( ) : [ S | undefined , Dispatch < SetStateAction < S | undefined > > , ReadOnlyRefObject < S | undefined > ] ; } ; const useStateRef = < S > ( initialState ? ) => { const [ state , setState ] = useState ( initialState ) ; const ref = useRef ( state ) ; const dispatch = useCallback ( ( setStateAction ) => { ref . current = isFunction ( setStateAction ) ? setStateAction ( ref . current ) : setStateAction ; setState ( ref . current ) ; } , [ ] ) ; return [ state , dispatch , ref ] ; } ; export = useStateRef ;