import { Dispatch, SetStateAction, useMemo, useState } from 'react'; import useProtect from './useProtect'; type SetStateFunction = Dispatch>; type SetStateParameters = Parameters>; type SetStateReturnType = ReturnType>; const useProtectedState = ( initialState: S | (() => S), protect?: ( fn: SetStateFunction, ...args: SetStateParameters ) => SetStateReturnType, ): [S, SetStateFunction] => { const { protect: defaultProtect } = useProtect(); const [state, setState] = useState(initialState); const pfn = useMemo( () => protect ?? defaultProtect, [defaultProtect, protect], ); return [ state, (...args: SetStateParameters): SetStateReturnType => pfn(setState, ...args), ]; }; export default useProtectedState;