useHooks.iov4.1.2
DocsBlogGitHub
Hooks
No hooks found in any category.

useToggle

state

Installation

npx usehooks-cli@latest add use-toggle

Description

A React hook for managing boolean toggle state with convenient methods for setting, toggling, and controlling the state.

Parameters

NameTypeDefaultDescription
initialValue?booleanfalseThe initial boolean value for the toggle

Return Type

UseToggleOutput
PropertyTypeDescription
isOnbooleanThe current toggle state
toggle() => voidToggle the current state (true becomes false, false becomes true)
setOn() => voidSet the state to true
setOff() => voidSet the state to false
set(value: boolean) => voidSet the state to a specific boolean value

Examples

Basic Toggle

Simple on/off toggle functionality

1const { isOn, toggle, setOn, setOff } = useToggle(); 2 3return ( 4 <div> 5 <p>Status: {isOn ? 'ON' : 'OFF'}</p> 6 <button onClick={toggle}>Toggle</button> 7 <button onClick={setOn}>Turn On</button> 8 <button onClick={setOff}>Turn Off</button> 9 </div> 10);

Modal Visibility

Using toggle for modal show/hide

1const { isOn: isModalOpen, toggle: toggleModal, setOff: closeModal } = useToggle(); 2 3return ( 4 <> 5 <button onClick={toggleModal}>Open Modal</button> 6 {isModalOpen && ( 7 <Modal onClose={closeModal}> 8 <p>Modal content</p> 9 </Modal> 10 )} 11 </> 12);

Dependencies

react

Notes

  • All methods are memoized with useCallback for optimal performance
  • Perfect for managing UI state like modals, dropdowns, and toggles
  • Can be used with custom initial values for different default states

Implementation

1"use client"; 2 3import { useState, useCallback } from "react"; 4 5interface UseToggleOutput { 6 isOn: boolean; 7 toggle: () => void; 8 setOn: () => void; 9 setOff: () => void; 10 set: (value: boolean) => void; 11} 12 13export const useToggle = (initialValue = false): UseToggleOutput => { 14 const [isOn, setIsOn] = useState<boolean>(initialValue); 15 16 const toggle = useCallback(() => { 17 setIsOn((prev) => !prev); 18 }, []); 19 20 const setOn = useCallback(() => { 21 setIsOn(true); 22 }, []); 23 24 const setOff = useCallback(() => { 25 setIsOn(false); 26 }, []); 27 28 const set = useCallback((value: boolean) => { 29 setIsOn(value); 30 }, []); 31 32 return { 33 isOn, 34 toggle, 35 setOn, 36 setOff, 37 set, 38 }; 39}; 40 41export default useToggle; 42