Installation
CLI
npx shadcn@latest add https://kelvinmai.io/r/use-boolean.json
Manual
Copy and paste the following code into your project
hooks/use-boolean.ts
'use client';import * as React from 'react';export function useBoolean(defaultValue = false) {if (typeof defaultValue !== 'boolean') {throw new Error('defaultValue must be `true` or `false`');}const [value, setValue] = React.useState(defaultValue);const setTrue = React.useCallback(() => {setValue(true);}, []);const setFalse = React.useCallback(() => {setValue(false);}, []);const toggle = React.useCallback(() => {setValue((x) => !x);}, []);return { value, setValue, setTrue, setFalse, toggle };}
Update the import paths to match your project setup
Usage
import { useMount } from '@/hooks/use-mounted';const mounted = useMounted();
API Reference
Parameters
Name | Type | Description |
---|---|---|
defaultValue? | boolean | An optional parameter for the initial value of the boolean. The default is set to false |
Returns
The useBoolean
hook returns an object with the following elements:
Name | Type | Description |
---|---|---|
value | boolean | The current boolean state value. |
setTrue | () => void | Function to set the boolean state to true . |
setFalse | () => void | Function to set the boolean state to false . |
toggle | () => void | Function to toggle the boolean state. |
setValue | Dispatch<SetStateAction<boolean>> | Function to directly set the boolean state. |