import { Dispatch, MutableRefObject, SetStateAction, useEffect, useRef, useState } from 'react' export type CurrentStateType = [S, Dispatch>, MutableRefObject] const useCurrentState = (initialState: S): CurrentStateType => { const [state, setState] = useState(initialState as S) 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