useToggle

A React hook for managing boolean state with convenient toggle actions.

Overview

useToggle simplifies boolean state management by providing a tuple with the current value and an object containing helper actions. Perfect for modals, dropdowns, accordions, theme switches, and any on/off UI patterns.

Demo

Day & Night Scene

Toggle between day mode with a simple boolean switch.

Interactive Scene
DayNight
isNight = false

API Reference

function useToggle(initialValue?: boolean): [
  boolean,
  {
    toggle: () => void,
    setTrue: () => void,
    setFalse: () => void,
    setValue: (value: boolean) => void
  }
]

Parameters

NameTypeDescription
initialValuebooleanOptional. Initial toggle state. Defaults to false.

Returns

NameTypeDescription
valuebooleanThe current boolean state.
toggle() => voidFlips the current value.
setTrue() => voidSets value to true.
setFalse() => voidSets value to false.
setValue(value: boolean) => voidSets value directly.

Usage Examples

import { useToggle } from 'react-hooks-ts'
 
function ModalExample() {
  const [isOpen, { setTrue: open, setFalse: close }] = useToggle()
 
  return (
    <>
      <button onClick={open}>Open Modal</button>
      {isOpen && <Modal onClose={close} />}
    </>
  )
}

Theme Switch

import { useToggle } from 'react-hooks-ts'
 
function ThemeSwitch() {
  const [isDark, { toggle }] = useToggle(false)
 
  return (
    <button onClick={toggle}>
      {isDark ? '🌙 Dark' : '☀️ Light'}
    </button>
  )
}

Features

  • 🎯 Simple API - Destructure only the actions you need.
  • 🔄 Memoized Actions - All functions maintain stable references.
  • Zero Dependencies - Lightweight and fast.
  • 💪 TypeScript Ready - Full type inference out of the box.