Files
react/components/use-current-state/use-current-state.ts
unix 4e7b4cc57d refactor: export all hooks functions directly from main module
refactor: rename the modules to make sure tree-shaking works
2020-05-16 23:04:57 +08:00

23 lines
680 B
TypeScript

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