UNPKG

common-hook

Version:
19 lines (18 loc) 715 B
import { useCallback, useState } from "react"; import { isFunction } from "common-screw"; /** * @name 管理 object 类型 state 的 Hooks * @description 用法与 class 组件的 this.setState 基本一致 * @example * const [state, setState] = useSetState<State>({hello: '',count: 0}) */ export const useSetState = (initialState) => { const [state, setState] = useState(initialState); const setMergeState = useCallback((patch) => { setState((prevState) => { const newState = isFunction(patch) ? patch(prevState) : patch; return newState ? Object.assign(Object.assign({}, prevState), newState) : prevState; }); }, []); return [state, setMergeState]; };