Skip to content

Commit 90a33f5

Browse files
authored
🐛: reject non-boolean value as a defaultValue for useBoolean (#561 by @luckrnx09)
* fix: reject non-boolean value as a defaultValue for `useBoolean` * add changeset
1 parent 7ba7e3a commit 90a33f5

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

.changeset/sharp-donkeys-impress.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"usehooks-ts": patch
3+
---
4+
5+
fix: reject non-boolean value as a defaultValue for useBoolean

packages/usehooks-ts/src/useBoolean/useBoolean.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,11 @@ describe('useBoolean()', () => {
8686

8787
expect(result.current.value).toBe(false)
8888
})
89+
90+
it('should throw an error', () => {
91+
const nonBoolean = '' as never
92+
expect(() => {
93+
renderHook(() => useBoolean(nonBoolean))
94+
}).toThrow('defaultValue must be `true` or `false`')
95+
})
8996
})

packages/usehooks-ts/src/useBoolean/useBoolean.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,19 @@ type UseBooleanReturn = {
2020
* Custom hook that handles boolean state with useful utility functions.
2121
* @param {boolean} [defaultValue] - The initial value for the boolean state (default is `false`).
2222
* @returns {UseBooleanReturn} An object containing the boolean state value and utility functions to manipulate the state.
23+
* @throws Will throw an error if `defaultValue` is an invalid boolean value.
2324
* @public
2425
* @see [Documentation](https://usehooks-ts.com/react-hook/use-boolean)
2526
* @example
2627
* ```tsx
2728
* const { value, setTrue, setFalse, toggle } = useBoolean(true);
2829
* ```
2930
*/
30-
export function useBoolean(defaultValue?: boolean): UseBooleanReturn {
31-
const [value, setValue] = useState(!!defaultValue)
31+
export function useBoolean(defaultValue = false): UseBooleanReturn {
32+
if (typeof defaultValue !== 'boolean') {
33+
throw new Error('defaultValue must be `true` or `false`')
34+
}
35+
const [value, setValue] = useState(defaultValue)
3236

3337
const setTrue = useCallback(() => {
3438
setValue(true)

0 commit comments

Comments
 (0)