useGetState
作用
给 React.useState
增加了一个 getter
方法,以获取当前最新值。
原理
通过
useRef
记录最新的state
的值,并暴露一个getState
方法获取到最新的state
的值。
源码
ts
import type { Dispatch, SetStateAction } from 'react'
import { useState, useRef, useCallback } from 'react'
type GetStateAction<S> = () => S
function useGetState<S>(
initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>, GetStateAction<S>]
function useGetState<S = undefined>(): [
S | undefined,
Dispatch<SetStateAction<S | undefined>>,
GetStateAction<S | undefined>
]
function useGetState<S>(initialState?: S) {
const [state, setState] = useState(initialState)
// 用来缓存state
const stateRef = useRef(state)
// 用来更新state
stateRef.current = state
// 用来获取最新的state
const getState = useCallback(() => stateRef.current, [])
// 返回state和更新和获取state的函数
return [state, setState, getState]
}
export default useGetState