Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvement: Update useBoolean hook to accept a function as defaultValue #528

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chilly-frogs-obey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"usehooks-ts": patch
---

✨ Improvement: update `useBoolean` hook
24 changes: 20 additions & 4 deletions packages/usehooks-ts/src/useBoolean/useBoolean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useCallback, useState } from 'react'
import type { Dispatch, SetStateAction } from 'react'

interface UseBooleanOutput {
value: boolean
value: boolean | (() => boolean)
setValue: Dispatch<SetStateAction<boolean>>
setTrue: () => void
setFalse: () => void
Expand All @@ -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.
Expand All @@ -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)
Expand Down