Custom useToggle hook with optional initial state
Hookshookbooleanstatetogglecustom-hook
A lightweight, reusable React hook for managing boolean toggle state with optional initial value.
TSX
import { useState, useCallback } from 'react';
function useToggle(initialValue: boolean = false) {
const [value, setValue] = useState<boolean>(initialValue);
const toggle = useCallback(() => {
setValue(prev => !prev);
}, []);
const setTrue = useCallback(() => {
setValue(true);
}, []);
const setFalse = useCallback(() => {
setValue(false);
}, []);
return [value, { toggle, setTrue, setFalse }] as const;
}
export default useToggle;Use useToggle() to get a boolean value and an object with toggle, setTrue, and setFalse functions. Pass an optional initialValue (defaults to false). Destructure like const [isActive, { toggle, setTrue }] = useToggle(true);. All callbacks are memoized with useCallback, so they’re safe for dependency arrays or prop passing. Note: the returned array uses as const for precise TypeScript inference.