Function: useToggleState()
useToggleState(
initialState?): [boolean, () =>void,Dispatch<SetStateAction<boolean>>]
Defined in: use-toggle-state.ts:40
A custom React hook for toggling a boolean state.
This hook is useful for managing binary states, such as showing/hiding elements, toggling themes, or activating/deactivating features.
Parameters
initialState?
boolean = false
The initial state of the toggle (default is false).
Returns
[boolean, () => void, Dispatch<SetStateAction<boolean>>]
A tuple of the current state, a stable toggle function, and a stable setState for setting an explicit value (for example setOpen(false) to close).
Examples
const [isVisible, toggleVisibility] = useToggleState(false);
return (
<div>
<button onClick={toggleVisibility}>
{isVisible ? "Hide" : "Show"} Content
</button>
{isVisible && <p>This is some toggleable content!</p>}
</div>
);
const [isOpen, toggleOpen, setOpen] = useToggleState();
return (
<>
<button onClick={toggleOpen}>Menu</button>
{isOpen && <Menu onSelect={() => setOpen(false)} />}
</>
);
For a live, editable example, see the useToggleState docs page.