Docs
useToggle

Easily manage a boolean state with useToggle.

Installation

pnpm dlx shadcn@latest add https://hookcn.ouassim.tech/r/use-toggle

Usage

import { useToggle } from "@/hooks/use-toggle"
 
export function Component() {
  const [value, toggle, setValue] = useToggle()
 
  // Just an example to use "setValue"
  const customToggle = () => {
    setValue((x: boolean) => !x)
  }
 
  return (
    <>
      <p>
        Value is <code>{value.toString()}</code>
      </p>
      <button
        onClick={() => {
          setValue(true)
        }}
      >
        set true
      </button>
      <button
        onClick={() => {
          setValue(false)
        }}
      >
        set false
      </button>
      <button onClick={toggle}>toggle</button>
      <button onClick={customToggle}>custom toggle</button>
    </>
  )
}

API Reference

Parameters

NameTypeDescription
defaultValue?booleanThe initial value for the toggle state.

Returns

The useToggle hook returns a tuple with the following elements:

IndexTypeDescription
0booleanThe current toggle state value.
1() => voidFunction to toggle the state.
2Dispatch<SetStateAction<boolean>>Function to set the toggle state directly.