diff --git a/packages/hooks/src/useSetState/__tests__/index.spec.ts b/packages/hooks/src/useSetState/__tests__/index.spec.ts index dd58721335..4a236063a9 100644 --- a/packages/hooks/src/useSetState/__tests__/index.spec.ts +++ b/packages/hooks/src/useSetState/__tests__/index.spec.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from 'vitest'; import useSetState from '../index'; describe('useSetState', () => { - const setUp = (initialValue: T) => + const setUp = (initialValue?: T) => renderHook(() => { const [state, setState] = useSetState(initialValue); return { @@ -38,4 +38,22 @@ describe('useSetState', () => { }); expect(hook.result.current.state).toEqual({ count: 1 }); }); + + test('should support empty initial state', () => { + const hook = renderHook(() => { + const [state, setState] = useSetState<{ hello?: string }>(); + return { + state, + setState, + } as const; + }); + + expect(hook.result.current.state).toEqual({}); + + act(() => { + hook.result.current.setState({ hello: 'world' }); + }); + + expect(hook.result.current.state).toEqual({ hello: 'world' }); + }); }); diff --git a/packages/hooks/src/useSetState/index.en-US.md b/packages/hooks/src/useSetState/index.en-US.md index 6bfbf2d2f7..3cb9b686fd 100644 --- a/packages/hooks/src/useSetState/index.en-US.md +++ b/packages/hooks/src/useSetState/index.en-US.md @@ -20,7 +20,7 @@ useSetState works similar to `this.setState` of class component, used to manage ## API ```typescript -const [state, setState] = useSetState(initialState); +const [state, setState] = useSetState(initialState?); ``` ### Result @@ -34,4 +34,4 @@ const [state, setState] = useSetState(initialState); | Property | Description | Type | Default | | ------------ | ------------- | -------------- | ------- | -| initialState | Initial state | `T \| () => T` | - | +| initialState | Initial state | `T \| () => T` | `{}` | diff --git a/packages/hooks/src/useSetState/index.ts b/packages/hooks/src/useSetState/index.ts index ca8b0db2ba..8fbbdc4201 100644 --- a/packages/hooks/src/useSetState/index.ts +++ b/packages/hooks/src/useSetState/index.ts @@ -7,7 +7,7 @@ export type SetState> = ( ) => void; const useSetState = >( - initialState: S | (() => S), + initialState: S | (() => S) = {} as S, ): [S, SetState] => { const [state, setState] = useState(initialState); diff --git a/packages/hooks/src/useSetState/index.zh-CN.md b/packages/hooks/src/useSetState/index.zh-CN.md index c06c148b0f..f714fd1aff 100644 --- a/packages/hooks/src/useSetState/index.zh-CN.md +++ b/packages/hooks/src/useSetState/index.zh-CN.md @@ -20,7 +20,7 @@ nav: ## API ```typescript -const [state, setState] = useSetState(initialState); +const [state, setState] = useSetState(initialState?); ``` ### Result @@ -34,4 +34,4 @@ const [state, setState] = useSetState(initialState); | 参数 | 说明 | 类型 | 默认值 | | ------------ | -------- | -------------- | ------ | -| initialState | 初始状态 | `T \| () => T` | - | +| initialState | 初始状态 | `T \| () => T` | `{}` |