Skip to content

Commit

Permalink
Merge pull request #1390 from alibaba/ts/use-set-state
Browse files Browse the repository at this point in the history
fix: optimize useSetState ts
  • Loading branch information
awmleer authored Dec 21, 2021
2 parents 0a8b87c + 0ab66b4 commit 514456b
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions packages/hooks/src/useSetState/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import { useCallback, useState } from 'react';
import { isFunction } from '../utils';

const useSetState = <T extends Record<string, any>>(
initialState: T = {} as T,
): [T, (patch: Partial<T> | ((prevState: T) => Partial<T>)) => void] => {
const [state, setState] = useState<T>(initialState);
export type SetState<S extends Record<string, any>> = <K extends keyof S>(
state: Pick<S, K> | null | ((prevState: Readonly<S>) => Pick<S, K> | S | null),
) => void;

const useSetState = <S extends Record<string, any>>(
initialState: S | (() => S),
): [S, SetState<S>] => {
const [state, setState] = useState<S>(initialState);

const setMergeState = useCallback((patch) => {
setState((prevState) => ({ ...prevState, ...(isFunction(patch) ? patch(prevState) : patch) }));
setState((prevState) => {
const newState = isFunction(patch) ? patch(prevState) : patch;
return newState ? { ...prevState, ...newState } : prevState;
});
}, []);

return [state, setMergeState];
Expand Down

0 comments on commit 514456b

Please sign in to comment.