import { Dispatch, MutableRefObject, SetStateAction, useEffect, useRef, useState } from 'react' export type CurrentStateType = [S, Dispatch>, MutableRefObject] const useCurrentState = (initialState: S | (() => S)): CurrentStateType => { const [state, setState] = useState(() => { return typeof initialState === 'function' ? (initialState as () => S)() : initialState }) const ref = useRef(initialState as S) useEffect(() => { ref.current = state }, [state]) const setValue = (val: SetStateAction) => { const result = typeof val === 'function' ? (val as (prevState: S) => S)(ref.current) : val ref.current = result setState(result) } return [state, setValue, ref] } export default useCurrentState