diff --git a/src/useMergeState.ts b/src/useMergeState.ts index e06e790..eff7705 100644 --- a/src/useMergeState.ts +++ b/src/useMergeState.ts @@ -1,12 +1,12 @@ import { useState } from 'react' -type Updater = (state: TState) => Partial +type Updater = (state: TState) => Partial | null export type MergeStateSetter = ( update: Updater | Partial | null ) => void -export default function useMergeState( +export default function useMergeState( initialState: TState ): [TState, MergeStateSetter] { const [state, setState] = useState(initialState) @@ -14,7 +14,10 @@ export default function useMergeState( const updater = (update: Updater | Partial | null) => { if (update === null) return if (typeof update === 'function') - setState(state => ({ ...state, ...update(state) })) + setState(state => { + const nextState = update(state) + return nextState == null ? state : { ...state, ...nextState } + }) setState(state => ({ ...state, ...update })) }