wkkkis-hooks

use-toggle (use-toggle)

Controls a boolean state with a toggle function.

v0.1.0

Usage

import { use-toggle } from "@/hooks"
1"use client"; 2 3import React from "react"; 4 5import { Button } from "@/components/ui/button"; 6import { 7 Card, 8 CardContent, 9 CardDescription, 10 CardFooter, 11 CardHeader, 12 CardTitle, 13} from "@/components/ui/card"; 14 15import { useToggle } from "@/components/hooks/use-toggle"; 16 17export function UseToggleDemo() { 18 const [isOn, toggle] = useToggle(false); 19 20 return ( 21 <Card className="relative max-w-sm w-full"> 22 <CardHeader> 23 <CardTitle>useToggle</CardTitle> 24 <CardDescription> 25 This component uses the <code>useToggle</code> hook to toggle a 26 boolean state. 27 </CardDescription> 28 </CardHeader> 29 <CardContent> 30 <p> 31 The state is: <strong>{isOn ? "On" : "Off"}</strong> 32 </p> 33 </CardContent> 34 <CardFooter> 35 <Button onClick={toggle}>Toggle</Button> 36 </CardFooter> 37 </Card> 38 ); 39} 40

Install

npx wkkkis-hooks add use-toggle

Returns — Properties

NameTypeDefaultDescription
The hook returns a tuple[value, toggle] .
valueis the current boolean state.
toggleis a function that toggles the state between true and false .

onToggle Callback

  • The onToggle callback is called every time the state changes, with the new value as its argument.
  • The callback is called after the state is updated.

Returned Values

  • The hook returns a tuple: [value, toggle] .
  • value is the current boolean state.
  • toggle is a function that toggles the state between true and false .

Initial Value

  • The initialValue prop sets the initial state (defaults to false ).

Best Practices & Caveats

  • The hook is designed for toggling boolean state in React components.
  • For best performance, memoize the onToggle callback if it depends on other values.
  • The hook is client-side only.

Files in this hook

SourceDestination
files/use-toggle.tssrc/hooks/use-toggle.ts