useBoolean
EditManages a boolean with explicit true, false, and toggle controls.
import { useCallback, useState } from "react";
import type { Dispatch, SetStateAction } from "react";
export interface UseBooleanResult { readonly value: boolean; readonly setValue: Dispatch<SetStateAction<boolean>>; readonly setTrue: () => void; readonly setFalse: () => void; readonly toggle: () => void;}
export function useBoolean(initialValue = false): UseBooleanResult { if (typeof initialValue !== "boolean") { throw new TypeError("initialValue must be a boolean"); }
const [value, setInternalValue] = useState(initialValue); const setValue = useCallback<Dispatch<SetStateAction<boolean>>>((action) => { setInternalValue((current) => { const next = typeof action === "function" ? action(current) : action; if (typeof next !== "boolean") { throw new TypeError("value must be a boolean"); } return next; }); }, []); const setTrue = useCallback(() => setInternalValue(true), []); const setFalse = useCallback(() => setInternalValue(false), []); const toggle = useCallback( () => setInternalValue((current) => !current), [], );
return { value, setValue, setTrue, setFalse, toggle };}Download
Section titled “Download”wget -O src/hooks/useBoolean.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/react-hooks/useBoolean.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/react-hooks "$temp_dir" && mv "$temp_dir/useBoolean.ts" src/hooks/useBoolean.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { useBoolean } from "./useBoolean";
export function BooleanExample() { const { value, setTrue, setFalse, toggle } = useBoolean();
return ( <div> <p>The setting is {value ? "enabled" : "disabled"}.</p> <button type="button" onClick={setTrue}>Enable</button> <button type="button" onClick={setFalse}>Disable</button> <button type="button" onClick={toggle}>Toggle</button> </div> );}initialValue(boolean, default:false) — Initial state used on mount.
Returns
Section titled “Returns”UseBooleanResult with value, React-compatible setValue, setTrue,
setFalse, and toggle. Every control keeps a stable identity.