diff --git a/.changeset/chilly-frogs-obey.md b/.changeset/chilly-frogs-obey.md new file mode 100644 index 00000000..31111b7e --- /dev/null +++ b/.changeset/chilly-frogs-obey.md @@ -0,0 +1,5 @@ +--- +"usehooks-ts": patch +--- + +✨ Improvement: update `useBoolean` hook diff --git a/packages/usehooks-ts/src/useBoolean/useBoolean.ts b/packages/usehooks-ts/src/useBoolean/useBoolean.ts index 4e485ac3..f1f65e71 100644 --- a/packages/usehooks-ts/src/useBoolean/useBoolean.ts +++ b/packages/usehooks-ts/src/useBoolean/useBoolean.ts @@ -3,7 +3,7 @@ import { useCallback, useState } from 'react' import type { Dispatch, SetStateAction } from 'react' interface UseBooleanOutput { - value: boolean + value: boolean | (() => boolean) setValue: Dispatch> setTrue: () => void setFalse: () => void @@ -12,7 +12,7 @@ interface UseBooleanOutput { /** * Custom hook for handling boolean state with useful utility functions. - * @param {boolean} [defaultValue] - The initial value for the boolean state (default is `false`). + * @param {boolean | (() => boolean)} [defaultValue] - The initial boolean state value or a function that returns the initial value. * @returns {UseBooleanOutput} An object containing the boolean state value and utility functions to manipulate the state. * @property {boolean} value - The current boolean state value. * @property {Function} setValue - Function to set the boolean state directly. @@ -28,9 +28,25 @@ interface UseBooleanOutput { * console.log(value); // false * toggle(); * console.log(value); // true + * + * @example + * const { value, setTrue, setFalse, toggle } = useBoolean(() => true); + * + * console.log(value); // true + * setFalse(); + * console.log(value); // false + * toggle(); + * console.log(value); // true */ -export function useBoolean(defaultValue?: boolean): UseBooleanOutput { - const [value, setValue] = useState(!!defaultValue) +export function useBoolean( + defaultValue?: boolean | (() => boolean), +): UseBooleanOutput { + const [value, setValue] = useState(() => { + if (typeof defaultValue === 'function') { + return Boolean(defaultValue()) + } + return Boolean(defaultValue) + }) const setTrue = useCallback(() => { setValue(true)