diff --git a/packages/hooks/src/useGetState/demo/demo1.tsx b/packages/hooks/src/useGetState/demo/demo1.tsx index 119712b36e..8a50a86909 100644 --- a/packages/hooks/src/useGetState/demo/demo1.tsx +++ b/packages/hooks/src/useGetState/demo/demo1.tsx @@ -22,5 +22,5 @@ export default () => { }; }, []); - return ; + return ; }; diff --git a/packages/hooks/src/useGetState/index.ts b/packages/hooks/src/useGetState/index.ts index 51f76c61aa..64a1ed56f9 100644 --- a/packages/hooks/src/useGetState/index.ts +++ b/packages/hooks/src/useGetState/index.ts @@ -1,20 +1,26 @@ -import type { Dispatch, SetStateAction } from 'react'; +import type { Dispatch } from 'react'; import { useState, useRef, useCallback } from 'react'; +import { isFunction } from '../utils'; +type SetStateAction = Dispatch>; type GetStateAction = () => S; -function useGetState( - initialState: S | (() => S), -): [S, Dispatch>, GetStateAction]; +function useGetState(initialState: S | (() => S)): [S, SetStateAction, GetStateAction]; function useGetState(): [ S | undefined, - Dispatch>, + SetStateAction, GetStateAction, ]; function useGetState(initialState?: S) { - const [state, setState] = useState(initialState); + const [state, setInnerState] = useState(initialState); const stateRef = useRef(state); - stateRef.current = state; + + const setState = useCallback>((stateOrAction) => { + const newState = isFunction(stateOrAction) ? stateOrAction(stateRef.current) : stateOrAction; + + stateRef.current = newState; + setInnerState(newState); + }, []); const getState = useCallback(() => stateRef.current, []);