mirror of
https://github.com/zhigang1992/react.git
synced 2026-02-01 22:41:03 +08:00
23 lines
680 B
TypeScript
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
|