Skip to Content
ohooks

useToggle

Manages a boolean state with a toggle function that also accepts an explicit boolean or DOM event.

Loading preview...

The useToggle hook manages a boolean state and returns a [value, toggle, setValue] tuple where toggle flips the boolean when called with no arguments (or a React/DOM event) and sets an explicit boolean when passed true or false.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useToggle.json

Usage

Examples

Passing toggle Directly to onClick

Because toggle ignores non-boolean arguments like MouseEvent, you can pass it directly to onClick handlers without wrapping it in an arrow function.

Forcing an Explicit Boolean Value

Pass true or false to toggle(nextValue) (or use setValue) when you need to force a specific state.

API Reference

ToggleFn

Signature of the toggle function returned as the second tuple element.